Search code examples
permissionslaravel-8roles

How to check permissions in my controller


I'm new to Laravel and I'm writing a user management System on my own. At this time,

  • I can CRUD permissions, roles and users,
  • I can check the permissions by the AuthServiceProvider@boot method like this:
public function boot()
{
    Gate::before( function (User $user , $permission) {
        // App administrator
        if($user->getPermissions()->contains('appAll'))
        {
            return true;
        }
        // Permission check
        return $user->getPermissions()->contains($permission);
    });
}

In my AdminUserController, I can check the permissions like that:

public function index()
{
    if( Gate::check('createUser') || Gate::check('readUser') || Gate::check('updateUser') || Gate::check('deleteUser')) {
        return view('userMgmt/users/index', [
            'users' => User::getUsersWithRolesWithTexts()
        ]);
    }
    else
    {
        return redirect(route('home'))->withErrors('You do not have required permission');
    }
}

That is working well.

BUT Is this the right way to wrap each controller method with:

if( Gate::check(...) ...) {
    //Do what the method is supposed to do
}
else
{
    return redirect(route('SOME.ROUTE'))->withErrors('SOME ERROR OCCURRED');
}

It would be nice if someone can give me some ideas. Tank you


Solution

  • There is a controller helper function named authorize that you can call from any method in a controller that extends App\Http\Controllers\Controller. This method accepts the action name and the model, and it will throw an exception if the user is not authorized. So instead of the if...else statement, it will be one line:

    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);
    
        // The current user can update the blog post...
    }