I'm using Laravel 8 for my project and in this project and I have created a custom Middleware called Admin that goes like this:
public function handle(Request $request, Closure $next)
{
if (Auth::check()) {
if (Auth::user()->isAdmin()) {
return $next($request);
}
}
return redirect('/');
}
And I tried applying it like this:
Route::group(['middleware' => 'admin'], function() {
Route::resource('admin/users', App\Http\Controllers\Admin\AdminUserController::class);
});
And on Kernel.php:
'admin' => \App\Http\Middleware\Admin::class
So I called the isAdmin() at User Model which simply checks if the role of the user is correct or not:
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function isAdmin()
{
foreach ($this->roles as $role) {
if ($role->name == 'Manual User') {
return true;
}
}
return false;
}
Currently, I have these two roles:
And the user, that I want to log in, is set to 6 and has the role id of 1 which Manual User:
But now the problem is, when I go to /admin/users uri, it does not redirect me to ('/') uri and shows me /admin/users page!
So what is going wrong here? How can I fix this issue?
Note that the relationship between roles and users which is Many To Many works fine and there is no need to mention them.

