How I expose Laravel permissions in Vue.js

<h1 v-if="Laravel.user.can['manage users']">You have permission to manage users</h1>
<h1 v-else>You dont have permission to manage users</h1>

Configuration on backend

<script>
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
'user' => Auth::user()
]) !!};
</script>
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="user" content="Auth::user()">
let user = document.head.querySelector('meta[name="user"]');
<script>
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
'roles' => Auth::user()->roles
]) !!};
</script
Trait ExposePermissions
....


/**
* Get all user permissions.
*
* @return bool
*/
public function getAllPermissionsAttribute()
{
return $this->getAllPermissions();
}

/**
* Get all user permissions in a flat array.
*
* @return array
*/
public function getCanAttribute()
{
$permissions = [];
foreach (Permission::all() as $permission) {
if (Auth::user()->can($permission->name)) {
$permissions[$permission->name] = true;
} else {
$permissions[$permission->name] = false;
}
}
return $permissions;
}
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['all_permissions','can']

Front-end

<h1 v-if="Laravel.user.can['manage users']">You have permission to manage users</h1>
<h1 v-else>You dont have permission to manage users</h1>
<h1 v-if="user.can['manage users']">You have permission to manage users</h1>
<h1 v-else>You dont have permission to manage users</h1>

Security note

--

--

--

Computer Science Teacher and Open Source contributor in my free time. Creator of adminlte-laravel. https://acacha.github.io

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sergi Tur Badenas

Sergi Tur Badenas

Computer Science Teacher and Open Source contributor in my free time. Creator of adminlte-laravel. https://acacha.github.io

More from Medium

Laravel 9 released!

How to implement pagination in Laravel 9 + Inertia.js + Vue 3 stack

Running Laravel Out Of A Subdirectory

How To Display Flash Messages With Laravel 9 + Jetstream + Vue Inertia.JS