据我所知,在Laravel 5.3中,他们已弃用路由过滤器以支持中间件。这是讨论here。
我正在尝试做类似的事情而不是定义路由模式我想定义一个“过滤器”,我检查登录用户的某个条件,如果不满足这个条件,则重定向用户。我希望此过滤器全局应用于应用程序。
我该怎么做?我只看到Route :: pattern方法的文档,但Route :: filter不存在。
答案 0 :(得分:2)
您可以使用这样的Laravel Middleware:
要创建新的中间件,请使用make:middleware Artisan命令:
php artisan make:middleware CheckUserAge
您的CheckUserAge.php
课程应如下所示:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckUserAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (auth()->user->age <= 20) {
return redirect('home');
}
return $next($request);
}
}
如果您希望在对应用程序的每个HTTP请求期间运行中间件,只需在$middleware
类的app/Http/Kernel.php
属性中列出中间件类。
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
// insert your middleware here <--------------
'checkUserAge' => \App\Http\Middleware\CheckUserAge::class,
];
开箱即用,网络中间件组会自动应用于
routes/web.php
的{{1}}文件。
RouteServiceProvider
希望这有帮助!