Search code examples
laravelauthorizationlaravel-5.3

Laravel authorization using middleware


I have following tables:

Role Table

  1. ID
  2. Title

Permission Table

  1. ID
  2. Title
  3. Role_id
  4. Permissions ( like : {test:"create","edit","update","delete"} )

Now after logging in how can I check through middleware whether that specific user has above permissions, whether he can create/edit/update/delete.

I don't want to specify the permissions or role name in routes.

Route::group(['permission'=>'create-user'] ...

Instead want to check with the help of middleware.

Route::group(['middleware'=>'authorization'] ...

So that I don't have to specify individual permissions in route each time new role and permissions to those role has been added.

Thankyou


Solution

  • You need to create a middleware and in the handle method of that middleware just check for the permissions

    public function handle($request, Closure $next, $guard = null)
    {
        $records = DB::table('role_table')
                      ->join('permissions_table', 'role_table.ID', '=', 'permissions_table.Role_id')
                      ->select('permissions_table.Permissions')
                      ->first();
    
        if (count($records) > 0) {
    
            $permisssions = json_decode($records->Permissions, true);
    
            if (in_array("create", $permissions['test'])) {
               // has permission to create
               // redirect to the authorized page 
            }
            ...
    
        } else {
           return redirect('to access denied page');
        }
    
        return $next($request);
    }
    

    add the middleware to App\Http\Kernel.php $routeMiddleware array

    protected $routeMiddleware = [
     'authorization' => \App\Http\Middleware\AuthorizationMiddleware::class
    ];