在 Laravel 中像在 Lumen 中一样忽略路由参数

问题描述 投票:0回答:1

我一直在使用 Lumen,我注意到一个方便的功能,我可以忽略一些路由参数,并且参数将自动匹配参数的名称。然而,在 Laravel 中,这个选项似乎默认不可用。

例如:

Route::get('{category_id}/system/batches/{batch_id}', 'CirculyDb\Settings\BatchSettingController@show');

// controlloer method, category_id can be ignored  
public function show($batch_id): JsonResponse

有没有办法在 Laravel 中实现类似的行为,我可以忽略特定的路由参数并让它们自动匹配相应的参数名称?

php laravel lumen
1个回答
0
投票

在 Laravel 中,您可以通过在路由中使用可选参数来实现类似于 Lumen 的行为。官方文档提供了有关如何执行此操作的指导。假设您想让

category_id
参数成为可选参数,并让它自动匹配参数名称。以下是实现这一目标的方法:

Route::get('/{category_id?}/system/batches/{batch_id}', 'CirculyDb\Settings\BatchSettingController@show');

// Controller method with an optional parameter
public function show($batch_id, $category_id = null): JsonResponse
{
    // Your controller logic here
}

在此示例中,我们通过在路由定义中的名称后面添加

category_id
?
设为可选参数。控制器方法包含可选参数
$category_id
,默认值为
null
,这允许它匹配参数名称,并在 URI 中不存在
category_id
时自动将其设置为 null。这样,您就可以在 Laravel 中实现所需的行为,类似于您在 Lumen 中经历的情况。

© www.soinside.com 2019 - 2024. All rights reserved.