Regardless of whether you use Middleware, Request authorize method, Policies or Gates (which can be used as a Middleware), you would still need Role
model.
Roles
table will be the place you store all the roles and attach them to users by their name or slugs.
-
Create a Role
model.
If you're sure, that a user can only have 1 Role
, then add role_id
to your users
table.
- Add the relationships inside the
User
and Role
models.
User.php
public function role()
{
return $this->hasOne(Role::class);
}
Role.php
public function user()
{
return $this->belongsTo(User::class);
}
4. In your AuthServiceProvider.php
, you can define the gates:
(assuming role_id is not nullable)
Gate::define('do-this', function ($user) {
return in_array($user->role->name, DoThisClass::allowedRoles());
});
-
In your blades, you can check if the user has permission for certain tasks using @can directives.:
@can('do-this')
<button>You can definitely do this!</button>
@endcan
-
In your Routes, you can check if user is authorized by using Gates as a Middleware:
Route::group(['middleware' => ['can:do-this']], function () {
Route::get('do-this', 'DoThisController@action');
});
Why should you tie Gates with names rather than ID of Roles?
Since Roles can be deleted and it's super unreadable to use their ID, I would recommend using Role names.
The IDs can mismatch in the code and the databases when different enviroments are used.