Laravel SuperAdmin: Override All the Gates

If you use Gates in the Laravel project for roles/permissions, you can add one condition to override any gates, making a specific user a super-admin. Here's how.

Let's imagine you have this line in app/Providers/AuthServiceProvider.php, as per documentation:

1public function boot()
2{
3 Gate::define('update-post', function (User $user, Post $post) {
4 return $user->id === $post->user_id;
5 });
6}

And in this way, you define more gates like create-post, delete-post, and others.

But then, you want some User with, let's say, users.role_id == 1 to be able to do ANYTHING with the posts. And with other features, too. In other words, a super-admin.

All you need to do is, within the same boot() method, add these lines:

1Gate::before(function($user, $ability) {
2 if ($user->role_id == 1) {
3 return true;
4 }
5});

Depending on your logic of roles/permissions, you may change the condition, like this, for example:

1Gate::before(function($user, $ability) {
2 if ($user->hasPermission('root')) {
3 return true;
4 }
5});

In other words, for any $ability you return true if the User has a certain role or permission.

Then, Laravel wouldn't even check the Gate logic, and would just grant that user access.

Of course, be careful with that, cause one wrong condition and you may grant access to someone who is not a super-admin.

You can read more about Gates and permissions, in the official documentation.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord