如何在多重登录系统中使用中间件 [英] How to use Middleware in Multiple Login system
问题描述
我在laravel 5中使用不同的不同控制器(例如Account Controller和Admin controller)进行了多次登录.我想在路线上使用中间件来授权用户.我该怎么办?
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:创建AdminLoggedInMiddleware
php artisan make:middleware AdminLoggedInMiddleware
步骤2:在protected $routeMiddleware
数组的app\Http\Kernel.php
中注册AdminLoggedInMiddleware
.
Step 2: Register AdminLoggedInMiddleware
in app\Http\Kernel.php
in the protected $routeMiddleware
array.
protected $routeMiddleware = [
...,
'admin' => 'App\Http\Middleware\AdminLoggedInMiddleware',
];
第3步:检查Admin是否已登录,因此,打开AdminLoggedInMiddleware
并用以下内容替换默认的handle
方法:
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();
}
第4步:打开AdminController.php
文件并添加以下方法:
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.
这篇关于如何在多重登录系统中使用中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!