我一次只能使用一个中间件。在构造函数中..我想在构造函数或两个中间件中使用if else条件。
我只能在构造函数中使用中间件,如果其他条件也不起作用
示例如下
如果别的
class HRJob extends Controller
{
public function __construct()
{
if(Auth::guard('admin'))
{
$this->middleware('auth:admin');
}
else
{
$this->middleware('auth');
}
}
public function userdetails()
{
dd(Auth::user());
}
}
两个中间件
class HRJob extends Controller
{
public function __construct()
$this->middleware('auth:admin');
$this->middleware('auth');
}
public function userdetails()
{
dd(Auth::user());
}
}
在您的情况下,不需要两个中间件。
public function __construct()
{
$this->middleware('auth');
}
等同于你要做的任何事情,因为'auth'对'auth:admin'仍然有效。
但你仍然可以把你的中间件放在Routes文件(web.php / api.php)中
Route::group(['middleware'=>'auth:admin'],function (){
Route::get('/', 'HRJob@userdetailsAdmin');
});
Route::group(['middleware'=>'auth'],function (){
Route::get('/', 'HRJob@userdetails');
});
希望这可以帮助。
- -编辑 - -
在您的情况下,使用两个不同的auth表并且没有为“any auth”创建自定义中间件,您只是缺少check()方法:
if (Auth::guard('admin')->check()) {
$this->middleware('auth:admin');
} else {
$this->middleware('auth');
}
相当于
if (!Auth::guard('admin')->check()) {
$this->middleware('auth');
}