3
votes

I am trying to make laravel basic authorization. I'm using gate for laravel authorization.

Table structure

User Table, Permission Table, Role, role_permission table 

user : id, name , password, email
permission : id, name
role:id , name
role_permission: id, role_id, permission_id

authServiceProvider

public function boot(GateContract  $gate)
{
    $this->registerPolicies();

   foreach($this->getPermissions() as $permission)
    {
      $gate->define($permission->name,function($user) use($permission){  
      return $user->role->id == $permission->role_id;              
            });
    }       
}

public function getPermissions()
{

    $permissions = \DB::table('role_permission')
        ->join('permissions', 'permissions.id', '=', 'role_permission.permission_id')
        ->select('role_permission.*','permissions.*')
        ->get();
    return $permissions;

}

It doesn't work properly means I can't access the route though it's there in permission table with the appropriate user.

1
There's an uncommented dd() in there... Also, this is somewhat inefficient. You could query just the user's permissions, rather than every permission in your system.Stuart Wagner
Remove dd($permission) from your question as not needed.Onix
I removed it though..i think there is a problem of query with the user and roles..Hola
actually you did notOnix
Ok, I have updated..Now check pleaseHola

1 Answers

1
votes

You should not access database from service provider. Always try to keep your service provider simple. Please follow the bellow steps to serve your purpose.

AuthServiceProvider.class

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    $gate->before(function($user, $ability) {

          return $user->hasPermission($ability);
    });

}

Now add the following methods in App\User model.

public function hasPermission($name)
{
    $permission = Permission::where('name','=', $name)->first();
    if(! $permission) {
        return false;
    }

    return $this->hasRole($permission->roles);
} 

public function hasRole($role)
{
    if (is_string($role)) {
        return $this->roles->contains('name', $role);
    }

    return (bool) $role->intersect($this->roles)->count();
}

Hope this will work to serve your purpose.