How to separate user session from admin session in laravel?

Member

by addison , in category: PHP Frameworks , 5 months ago

How to separate user session from admin session in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 5 months ago

@addison 

In order to separate user session from admin session in Laravel, you can create two separate middleware groups for users and admins.


Here's how you can achieve this:

  1. Create a middleware for admin session:
1
php artisan make:middleware AdminMiddleware


  1. Define the logic for checking admin session in the AdminMiddleware:
1
2
3
4
5
6
7
8
public function handle($request, Closure $next)
{
    if (auth()->check() && auth()->user()->isAdmin()) {
        return $next($request);
    }

    return redirect()->route('login');
}


  1. Register the AdminMiddleware in your app/Http/Kernel.php file under the $routeMiddleware array:
1
'admin' => AppHttpMiddlewareAdminMiddleware::class,


  1. Create a route group for admin routes in your web.php file:
1
2
3
Route::middleware('admin')->group(function () {
    // Admin routes
});


  1. Use the auth middleware for user session in your routes:
1
2
3
Route::middleware('auth')->group(function () {
    // User routes
});


By following these steps, you can separate user session from admin session in Laravel and ensure that only admins have access to the routes defined within the admin middleware group.