Suppose I have page for searching cars, page takes 3 optional parameters, brand
, year
and color
Simplified route example:
Route::get('/cars/{brand?}/{year?}/{color?}', function ($brand = NULL, $year = NULL, $color = NULL) {
echo "brand is:".$brand."<br>";
echo "year is:".$year."<br>";
echo "color is:".$color."<br>";
});
I don't realise how to pass for example only year
parameter?
Works if passed all of 3 parameters, for example: /cars/_/2010/_
but this is very inelegant solution.
What is proper way for this ?
I don't know if this is possible since you may end up passing only 2 parameters and Laravel wouldn't be able to understand if this is brand
, color
or year
.
I will leave my two cents regarding on my method of URL parameters that I use:
public function getCars(Request $request){
Validator::validate($request->all(), [
'brand' => 'nullable|string',
'year' => 'nullable|integer',
'color' => 'nullable|string'
]);
$cars = Car::select('id', '...');
if($request->has('brand')){
// get cars with that brand
$cars->where('brand', $request->brand);
}
// ... and so on with the other parameters
$cars = $cars->paginate(10); // or $cars->get()
}
This is a fairly simple example so you will have to customize to your needs. Hope that helps.
As the official documentation says, Route parameters are injected into route callbacks / controllers based on their order. In this specific case, the only way Laravel has to know which is each parameter is like you suggest (see https://laravel.com/docs/5.6/routing#route-parameters).
Anyway, if 3 parameters are required to perform a search, you could probably think of changing the request verb from GET to POST, and pass all of them as POST request data instead of in the query string itself.