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:

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

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:

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

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

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

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:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses