Wakil Ahmed
Wakil Ahmed

Reputation: 1423

Passing multiple optional parameters in a route in Laravel

I have an a tag within a form that passes multiple optional parameters to the route. But when I skip one parameter in the middle and pass one after that it gives page not found.

How can I overcome this issue without using a form.

Here is my a tag:

<a href="{{ route('admin.employee.employeeListExcelExport', ['start_date' => $start_date, 'end_date' => $end_date, 'empId' => $empId, 'name' => $name] ) }}" class="btn btn-primary">Download</a>

My route:

Route::group(['prefix'=>'/employee','as'=>'employee.'], function(){
    Route::get('/', [EmployeeController::class, 'index'])->name('index');
    Route::get('/employee-list/excel-export/{start_date?}/{end_date?}/{empId?}/{name?}', [EmployeeController::class, 'employeeListExcelExport'])->name('employeeListExcelExport');
});

The reason I can't use form is because this tag is inside a form and it's not idea to use nested forms.

Upvotes: 0

Views: 595

Answers (1)

Erkan &#214;zk&#246;k
Erkan &#214;zk&#246;k

Reputation: 891

Change your route like this (clear optional parameters that you add to path):

Route::get('/employee-list/excel-export', [EmployeeController::class, 'employeeListExcelExport'])->name('employeeListExcelExport');

Now route helper method will generate a URL with query parameters, for example:

route('admin.employee.employeeListExcelExport', ['start_date' => $start_date, 'end_date' => $end_date, 'empId' => $empId, 'name' => $name] ) }}

// Returns 'http://localhost/employee/employee-list/excel-export?start_date=2022-09-12&end_date=2022-10-11&empId=3&name=erkan'

And now you can directly reach your optional parameters inside employeeListExcelExport method in EmployeeController

request()->get('start_date') or $request->get('start_date');

Upvotes: 1

Related Questions