user3207586
user3207586

Reputation: 141

Laravel optionnal parameters in routes

I want to have this two url working with one route:

mysite.com/search

and

mysite.com/food/search

I have done this but this is working only with the second one.

Route::group([ 'prefix' => '{section?}' ], function(){
    Route::get('/search', [ 'as' => 'search', 'uses' => 'PostController@search' ]);
});

Upvotes: 0

Views: 82

Answers (2)

Ozu
Ozu

Reputation: 58

Why you don't use mysite.com/search/food instead of mysite.com/food/search ?

By doing that , You will have now multiple solution for your routes one of these :

Route::group( [ 'prefix' => 'search' ], function() {
     //your code

     //as an example 
     Route::get('/',....);
     Route::get('/food' , ... ) ;
});

This will make your url more Human reading and easy to add features to it .

Upvotes: 2

pipedreams2
pipedreams2

Reputation: 628

I dont believe in this situation it is necessary to block it into a group. There are several approaches for wildcard routing in laravel.

Using a slug:

Route::get('{section?}/search', [ 'as' => 'search', 'PostController@search']);

Using a wildcard:

Route::get('(:any?)/search', ['as' => 'search', 'PostController@search']);

Using Regular Expressions:

Route::get('(.*)/search', ['as' => 'search', 'PostController@search']);

Obviously if you want to do handling of the wildcard you will need to pass a parameter into your search method in the PostController.

I haven't used Laravel in a while so this may be fuzzy but I think this should solve your problem.

Upvotes: 1

Related Questions