Laravel 如果可选参数不在列表中,则处理默认路由
Laravel handle default route if optional parameter is not in the list
我在路由中定义可选参数 "type" 并使用 where 子句限制可接受的值(A、B 或 C):
Route::get('test/{type?}', ['uses' => 'MyController@index'])->where('type', 'A|B|C');
如果类型值不同于 A、B 或 C(例如 "X")框架 returns 错误页面:
NotFoundHttpException in RouteCollection.php
在这种情况下,我想忽略收到的可选参数并处理没有指定参数的路由,即:test/
如何实现?
通过允许不在正则表达式条件中的类型参数值,意味着 where
方法在这种情况下是无用的。但是,您可以将逻辑移至中间件并在那里处理。以下是步骤:
1. 创建一个新的中间件,我们称它为 OptionalType
,在你的 Laravel 目录中通过 运行 这个命令:
php artisan make:middleware OptionalType
2. 之前的命令在 app/Http/Middleware
中创建了一个名为 OptionalType.php
的文件。该文件的内容应如下所示:
namespace App\Http\Middleware;
use Closure;
class OptionalType
{
protected $allowedTypes = ['A', 'B', 'C'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$route = $request->route();
// If the `type` parameter value is not within the allowed list
// set the value to `null` which is as if it was not passed
if (!in_array($route->parameter('type'), $this->allowedTypes)) {
$route->setParameter('type', null);
}
return $next($request);
}
}
3. 接下来需要在app/Http/Kernel.php
:
中将中间件注册为路由中间件
protected $routeMiddleware = [
...
'type' => \App\Http\Middleware\OptionalType::class,
];
4. 现在您可以将中间件添加到您的路由中(不再需要 where
条件,因为逻辑现在在中间件中):
Route::get('test/{type?}', ['middleware' => 'type', 'uses' => 'MyController@index']);
现在,当您将 A
、B
或 C
以外的任何内容传递给路由时,参数将变为 null
,就好像它甚至没有传递一样.
您可以在 Laravel Documentation 阅读更多关于中间件的信息。
我在路由中定义可选参数 "type" 并使用 where 子句限制可接受的值(A、B 或 C):
Route::get('test/{type?}', ['uses' => 'MyController@index'])->where('type', 'A|B|C');
如果类型值不同于 A、B 或 C(例如 "X")框架 returns 错误页面:
NotFoundHttpException in RouteCollection.php
在这种情况下,我想忽略收到的可选参数并处理没有指定参数的路由,即:test/
如何实现?
通过允许不在正则表达式条件中的类型参数值,意味着 where
方法在这种情况下是无用的。但是,您可以将逻辑移至中间件并在那里处理。以下是步骤:
1. 创建一个新的中间件,我们称它为 OptionalType
,在你的 Laravel 目录中通过 运行 这个命令:
php artisan make:middleware OptionalType
2. 之前的命令在 app/Http/Middleware
中创建了一个名为 OptionalType.php
的文件。该文件的内容应如下所示:
namespace App\Http\Middleware;
use Closure;
class OptionalType
{
protected $allowedTypes = ['A', 'B', 'C'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$route = $request->route();
// If the `type` parameter value is not within the allowed list
// set the value to `null` which is as if it was not passed
if (!in_array($route->parameter('type'), $this->allowedTypes)) {
$route->setParameter('type', null);
}
return $next($request);
}
}
3. 接下来需要在app/Http/Kernel.php
:
protected $routeMiddleware = [
...
'type' => \App\Http\Middleware\OptionalType::class,
];
4. 现在您可以将中间件添加到您的路由中(不再需要 where
条件,因为逻辑现在在中间件中):
Route::get('test/{type?}', ['middleware' => 'type', 'uses' => 'MyController@index']);
现在,当您将 A
、B
或 C
以外的任何内容传递给路由时,参数将变为 null
,就好像它甚至没有传递一样.
您可以在 Laravel Documentation 阅读更多关于中间件的信息。