如何用中间件要求中间件?
How to require middleware with a middleware?
我创建了一个中间件,比如 AuthenticateAdmin,在 Kernel.php 中我添加了代码:
'auth_admin' => \App\Http\Middleware\AuthenticateAdmin::class,
在我的路线中我有这个代码:
Route::group(['middleware' => 'auth_admin'], function () {
// Admin routes here
});
在我的 AuthenticateAdmin.php 我有这个代码
<?php namespace App\Http\Middleware;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class AuthenticateAdmin {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Perform action here
return $next($request);
}
}
我想做的是每次我使用中间件 'auth_admin',在进入 'auth_admin' 中间件之前,我希望它首先执行 'auth' 中间件。
我不确定你为什么需要这样做。但是在 Laravel 中,我认为你可以像下面这样配置以使其工作:
Route::group(['middleware' => ['auth','auth_admin']], function () {
// Admin routes here
});
您可以尝试使用依赖注入,在构造函数中您应该放置 auth
中间件,然后执行 auth_admin
的操作
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class AuthenticateAdmin {
/**
* Create a new authentication controller instance.
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Perform action here
return $next($request);
}
}
还有一件事,请记住遵循 PSR-2 标准,将命名空间放在下一行,就像我在示例中所做的那样。
我创建了一个中间件,比如 AuthenticateAdmin,在 Kernel.php 中我添加了代码:
'auth_admin' => \App\Http\Middleware\AuthenticateAdmin::class,
在我的路线中我有这个代码:
Route::group(['middleware' => 'auth_admin'], function () {
// Admin routes here
});
在我的 AuthenticateAdmin.php 我有这个代码
<?php namespace App\Http\Middleware;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class AuthenticateAdmin {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Perform action here
return $next($request);
}
}
我想做的是每次我使用中间件 'auth_admin',在进入 'auth_admin' 中间件之前,我希望它首先执行 'auth' 中间件。
我不确定你为什么需要这样做。但是在 Laravel 中,我认为你可以像下面这样配置以使其工作:
Route::group(['middleware' => ['auth','auth_admin']], function () {
// Admin routes here
});
您可以尝试使用依赖注入,在构造函数中您应该放置 auth
中间件,然后执行 auth_admin
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class AuthenticateAdmin {
/**
* Create a new authentication controller instance.
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Perform action here
return $next($request);
}
}
还有一件事,请记住遵循 PSR-2 标准,将命名空间放在下一行,就像我在示例中所做的那样。