Vue.js with Laravel Permission

后端 未结 5 639
旧时难觅i
旧时难觅i 2020-12-31 22:38

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

5条回答
  •  太阳男子
    2020-12-31 23:06

    Just stumbled upon this problem and I would like to share what I found and implemented.

    1. Add an accessor on the User model the spatie/laravel-permission is using
        public function getAllPermissionsAttribute() {
           $permissions = [];
             foreach (Permission::all() as $permission) {
               if (Auth::user()->can($permission->name)) {
                 $permissions[] = $permission->name;
               }
             }
           return $permissions;
        }
    
    1. On your global page or layout page pass the permission from the accessor to the javascript.
        
    
    1. Create a global directive on resources/js/app.js
        Vue.directive('can', function (el, binding, vnode) {
    
            if(Permissions.indexOf(binding.value) !== -1){
               return vnode.elm.hidden = false;
            }else{
               return vnode.elm.hidden = true;
            }
        })
    

    Here you are checking if the permission you supplied on the directive is on the permission array from laravel. If found then it will hide the element else show, this function is like a v-if.

    1. Use it like this on your component - "add_items" is your permission
        
    

    This solution is from this but instead of a mixin, I use a directive. Got the idea of directive from @Ismoil Shifoev comment above.

提交回复
热议问题