Search code examples
phplaraveleloquentpermissionseloquent-relationship

How to deploy relationship in pivot of three model in laravel?


I'm developing a role and permissions based on laravel framework.

I have 3 models :

Weblog
User
Permissions

This is pivot table

user_id , weblog_id , permission_id

Now, a user can have a weblog with permission id 1,2 and another weblog with permission 1,2,3,4

How can I deploy relationships? and how can I check user permissions when managing a weblog. (middleware and ...)


Solution

  • With the fact that Permission are specific to Weblog

    Say the pivot table is called permission_user_weblog

    class User extends Model
    {
        public function weblogs()
        {
            return $this->belongsToMany(Weblog::class, 'permission_user_weblog');
        }
    
        public function permissionsFor(int $weblogId)
        {
            $permissionIds = null;
    
            $this->weblogs()
                ->where('id', $weblogId)
                ->with('permissions')
                ->get()
                ->each(function($weblog) use(&$permissionIds) {
                    $permissionIds = $weblog->permissions->pluck('id');             
                });
    
            return $permissionIds;
        }
    }
    
    
    class Weblog extends Model
    {
        public function users()
        {
            return $this->belongsToMany(User::class, 'permission_user_weblog');
        }
    
        public function permissions()
        {
            return $this->belongsToMany(Permission::class, 'permission_user_weblog');
        }
    }
    
    
    class Permission extends Model
    {
        public function weblogs()
        {
            return $this->belongsToMany(Weblog::class, 'permission_user_weblog');
        }
    }
    

    Then you can check anywhere for whether logged in user has specific permission for a specific weblog

    public function update(Request $request, $weblogId)
    {
        $user = auth()->user();
        $permissions = $user->permissionsFor($weblogId);
    
        //Check whether the logged in user has permission identified by id 1 or 4 for weblog
        $can = !! $permissions->intersect([1,4])->count();
    
        //Do rest of processing
    }