I’m creating custom admin panel in Laravel and trying to make redirect to login page for unathorized users. There is so many posts about it in the web, but they are for older versions of Laravel and I couldnt find anything for 10. Here is web.php:
Route::middleware(['role:admin'])->prefix('admin')->group(function()
{
Route::get('/', [AppHttpControllersAdminHomeController::class, 'index'])->name('admin');
Route::resource('games', AppHttpControllersAdminPostController::class);
});
What should I add here to redirect users to login page?
2
Answers
I suppose you use Spatielaravel-permissions based on role:admin middleware.
You have to make your own middleware, for example "IsAdmin"
and then code authorization logic in the handle() function of your new middleware.
The hasRole() method is from laravel-permissions package, if you have other system for permissions then edit this logic.
Add your new middleware to your route. Also you should add Laravel auth middleware to check if user is authenticated.
To redirect unauthorized users to the login page in Laravel 10, you can use the built-in auth middleware along with any custom middleware for role checking.
web.php
Create a custom middleware
EnsureUserHasRole.php
Register the middleware in Http/Kernel.php.