Warm tip: This article is reproduced from serverfault.com, please click

Centralize user role verification in laravel

发布于 2020-11-29 07:00:38

I'm working on an e-commerce website and i need to display certain data based on the user role. Basically the page can be viewed by three types of people: normal people who enters the page and by a client user or an admin who have their accounts but they see different buttons/data according to their role. I'm working with jetstream authenticaton system and what i do is simply verify the user role on my views like this:

@if (Auth::user()->role->name == 'admin')
    //display button only the admin can see
@else
    //display button only a client user can see
@endif       

My question is, can i implement something like a gate to centralize the condition?, i mean, in case i need to change it only doing it in one file and avoid to do it in all the lines where i implented it. Any help is welcome. Thanks!

Questioner
Abraham Arreola
Viewed
0
tamrat 2020-11-29 17:19:02

Yes. Just define gates or use a model policy. Using gates, you can do something like (using a Post model as an example):

Gate::define('edit-post', function (User $user, Post $post) {
  return $user->role->name == 'admin' || $user->id == $post->user_id;
});


Gate::define('delete-post', function (User $user, Post $post) {
  return $user->role->name == 'admin';
});

And use it in your .blade.php files using the @can blade directives.

@can('edit-post')
// show an edit button
@endcan

@can('delete-post')
// show a delete button
@endcan

Here we are basically creating two controls for editing and deleting a post. To edit a post (or rather see the edit button), you either have to be an admin or the user must have created the post. To delete it, you have to be an admin.

References: Laravel Documentation on Authorization