Home > Software engineering >  Passing multiple optional parameters in a route in Laravel
Passing multiple optional parameters in a route in Laravel

Time:09-23

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] ) }}" >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.

CodePudding user response:

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');
  • Related