I have multiple routes that will directed to the same controller and method. I want the second route will have empty customParams, but the first one will use the custom params. What should I do? Thanks
Route::get('{customParams?}/{slug}/{registrationCode}/detail', [SubmissionController::class, 'submissionDetail'])->name('submission.detail');
public function submissionDetail($customParams = '', $slug, $registrationCode)
{
//
}
The first route was running perfectly
<a href="{{ route('submission.detail', ['customParams' => 'riwayat-pengajuan', 'slug' => $cs->service->slug, 'registrationCode' => $cs->registration_code]) }}" class="btn btn-primary btn-sm">Detail</a>
The second route did not work and produced a 404 page
<a href="{{ route('submission.detail', ['slug' => $cd->service->slug, 'registrationCode' => $cd->registration_code]) }}" class="btn btn-primary btn-sm">Detail</a>
My Answer:
To achieve this, you can define two separate routes in your routes file with different parameter requirements. Here's how you can modify your routes and controller method:
php
Route::get('{customParams}/{slug}/{registrationCode}/detail', [SubmissionController::class, 'submissionDetail'])->name('submission.detail.withParams');
Route::get('{slug}/{registrationCode}/detail', [SubmissionController::class, 'submissionDetail'])->name('submission.detail');
public function submissionDetail($slug, $registrationCode, $customParams = '')
{
//
}
With this setup, the first route `submission.detail.withParams` will expect the `customParams` parameter, while the second route `submission.detail` will not require the `customParams` parameter.
You can then use the routes in your views like this:
For the first route:
html
Detail
For the second route:
html
Detail
This way, the second route will work without the `customParams` parameter and the first route will work with the `customParams` parameter.
Rate this post
4 of 5 based on 5140 votesComments