Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js with Laravel Permission

I am in the process of integrating Laravel Permission API with Vue.JS frontend. I am using https://github.com/spatie/laravel-permission library for Laravel Permission. I am not understanding how can I check permission in the Vue JS front End (In Laravel blade I am using @Can to check the permission).

like image 902
Kapil Yamakanmardi Avatar asked Nov 15 '18 05:11

Kapil Yamakanmardi


2 Answers

I will do a ajax call to check for permissions instead , something like this, but of cours eyou need to modify it to cater your needs.

Routes:

Route::get('/permission/{permissionName}', 'PermissionController@check');

Controller:

function check($permissionName) {
   if (! Auth::user()->hasPermissionTo($permissionName)) {
        abort(403);
   }
   return response('', 204);
}

Vue: (if you wanna do this synchronously), this is a simple example (Vue global mixin), you can turn this into Vue directive or component.

Vue.mixin("can", (permissionName) => {
    let hasAccess;
    axios.get(`/permission/${permissionName}`)
        .then(()=> {
            hasAccess = true;
        }
        .catch(()=> {
            hasAccess = false;
        };
    return hasAccess;
});

And then everytime you wanna check permission, you can just do

<el-input v-if="can('write-stuff')"> </el-input>
like image 69
Shuyi Avatar answered Oct 19 '22 05:10

Shuyi


I'm literally working on this exact same thing. I'm thinking of adding a custom Vue directive that would check against the Laravel.permissions array.

It might even be as simple as

 Vue.directive('can', function (el, binding) {
  return Laravel.permissions.indexOf(binding) !== -1;
})

I haven't tested this code. Just brainstorming here.

<button v-can="editStuff">You can edit this thing</button>

I can hold permissions this way:

window.Laravel = <?php echo json_encode([
                'csrfToken' => csrf_token(),
                'userId' => Auth::user()->id,
                'permissions' => Auth::user()->permissions()->pluck('name')->toArray()
            ]); ?>
like image 5
Ismoil Shifoev Avatar answered Oct 19 '22 05:10

Ismoil Shifoev