Vue.js with Laravel Permission

Kapil Yamakanmardi picture Kapil Yamakanmardi · Nov 15, 2018 · Viewed 8.6k times · Source

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).

Answer

Shuyi picture Shuyi · Feb 12, 2019

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>