InvalidSyntax
InvalidSyntax

Reputation: 9495

How do I define an optional parameter in my Laravel routes?

I would like to define {id} an optional parameter in the following route:

Route::get('profile/edit/{id}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));

How can I do this and also define a default parameter if one isn't provided?

Upvotes: 1

Views: 87

Answers (3)

FULL STACK DEV
FULL STACK DEV

Reputation: 15941

Route::get('profile/edit/{id?}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));

you can pass {id?} for optional parameters in your route.

Laravel will take it as a optional. it is called as a wild card in laravel

Upvotes: 0

online Thomas
online Thomas

Reputation: 9381

Just like the other answers, but as for the default part: I asked almost the same question a few days ago and the answer is:

Route::get('profile/edit/{id?}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'))
    ->defaults('id', 'defaultValue');

The important things are

  • The questionmark
  • The defaults function

Upvotes: 1

Joel Hinz
Joel Hinz

Reputation: 25374

Just put a question mark after it in the route, and give it a default in the function:

Route::get('profile/edit/{id?}', ...
public function editProfile ($id = 123) { ... }

Documentation: https://laravel.com/docs/5.4/routing#parameters-optional-parameters

Upvotes: 0

Related Questions