我在路由中定义可选参数“type”,并使用 where 子句限制可接受的值(A、B 或 C):
Route::get('test/{type?}', ['uses' => 'MyController@index'])->where('type', 'A|B|C');
如果类型值与 A、B 或 C 不同(例如“X”),框架将返回错误页面:
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中阅读有关中间件的更多信息。 .
关于php - 如果可选参数不在列表中,Laravel 处理默认路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35103195/