[英]Optional parameter on laravel route
I have a route like this.我有这样的路线。 I want the first parameter will be an optional parameter.
我希望第一个参数是可选参数。 For example: students/service/123/detail & service/123/detail.
例如:students/service/123/detail & service/123/detail。 What should I do?
我应该怎么办? Thanks in advance.
提前致谢。
Route::get('{optionalParam}/{slug}/{registrationCode}/detail', [SubmissionController::class, 'submissionDetail'])->name('submission.detail');
Following the official documentation , optionals parameters are in the last position.按照官方文档,options参数在最后的position中。
The reason is simple.原因很简单。 For example this route:
例如这条路线:
Route::get('{param1?}/{param2}/{param3}
If you pass nothing as param1
, then param2
will become param1
.如果您什么都不传递
param1
,那么param2
将变为param1
。 So I advice you to use the same route, with a required parameter like this:所以我建议你使用相同的路线,需要这样的参数:
Route::get('{optionalParam}/{slug}/{registrationCode}/detail', [SubmissionController::class, 'submissionDetail'])->name('submission.detail');
And after in your controller, check if this parameter is the default you defined or not.在你的 controller 之后,检查这个参数是否是你定义的默认值。 For example, you can define a default value, like
0
and this value will indicate you that this parameter doesn't exist:例如,您可以定义一个默认值,如
0
,此值将指示您此参数不存在:
public function test($optionalParam, $slug, $registrationCode)
{
if ($optionalParam === 0) {
// here the parameter doesn't exist
}
// here the parameter exists
}
You can't have an optional parameter before mandatory parameters.在强制参数之前不能有可选参数。 Make
registrationCode
optional:使
registrationCode
可选:
Route::get('{optionalParam}/{slug}/{registrationCode?}/detail', [SubmissionController::class, 'submissionDetail'])->name('submission.detail');
and change your submissionDetail
method to be as:并将您的
submissionDetail
方法更改为:
public function submissionDetail($optionalParam, $slug, $registrationCode=null) {
if ($registrationCode === null) {
$registrationCode = $slug;
$slug = $optionalParam;
$optionalParam = null;
}
// Rest of method
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.