How can I manage controller methods according to user role in laravel?

public function __construct()
{
    $this->middleware('roles:Author')->only(['index','show','create']);
    $this->middleware('roles:User')->only(['index','show']);
}

      

In my controller, I want the accessor methods to execute according to the user's role, for example, if the user's role is administrator, then it should access all the controller's methods, if the user role belongs to Author, then it has access to the index, create method and show, and if the role is User, then he only has access to the index and show methods.

+3


source to share


1 answer


You can take a look Gates

( docs ).

In App\Providers\AuthServiceProvider

add:

Gate::define('create-post', function ($user) {
    return $user->isAuthor(); //Here you should check the users role
});

      



And then in your controller method create()

:

if (Gate::allows('create-post', $post)) {
    // The current user can create posts...
}

      

The other two methods: index()

and show()

are available for both roles, so no action is required.

+1


source







All Articles