How to use Middleware in Multiple Login system

2019-06-11 08:46发布

问题:

I have MUltiple login in laravel 5 with using differeent different controller like that Account controller and Admin controller . i want to use Middleware on route for authorize the user. what can i do ?

回答1:

Step 1: Create the AdminLoggedInMiddleware

php artisan make:middleware AdminLoggedInMiddleware

Step 2: Register AdminLoggedInMiddleware in app\Http\Kernel.php in the protected $routeMiddleware array.

protected $routeMiddleware = [
    ...,
    'admin' => 'App\Http\Middleware\AdminLoggedInMiddleware',
];

Step 3: Check if Admin is logged in, so, open AdminLoggedInMiddleware and replace the default handle method with this:

public function handle($request, Closure $next)
{
    // Change this condition as per your requirement.
    if ( Auth::check() && Auth::user()->role === 'administrator' ) {
        return $next($request);
    }
    return redirect()->back();
}

Step 4: Open your AdminController.php file and add the following method:

public function __construct()
{
    $this->middleware('admin');
}

Similarly, you can create the other middleware for your other user(s) and check if they are logged in or not.



标签: laravel-5