In Laravel, optional parameter is a fantastic way to save both time and work to write route and controller methods. By using optional parameter you can use same route and controller for multiple operation. For a regular route with parameter we write
Route::get('/user/{id}', [UserController::class, 'show']);
Here, id is the parameter to be passed with the route url “/user/”. But when we use a “?” after the id like following
Route::get('/user/{id?}', [UserController::class, 'show']);
Here the id parameter becomes optional. That means if the route is called without the id being passed, It will work fine. But in normal case this will definitely throw an error like “0 parameter passed , 1 expected”
Convention of writing optional parameter in Route:
In route, the optional parameter must always come after normal parameter. Otherwise it will create an error. For an instance
Route::get('/user/{id1}/{id2?}', [UserController::class, 'show']);
Optional parameter in Route-Model Binding:
Optional parameter method can also be used for route-model binding. For an instance, If there is a model named Consumer, then in a route the model parameter can be made optional like following.
Route::get('/consumer-list/{consumer?}', [PostController::class, 'display']);
How to use optional parameter in Controller:
Route::get('/user/{id?}', [UserController::class, 'show'])->name('user.show');
Now, We will examine two cases of route calling from blade.
Now, In the controller at first the optional parameter id must be initialized with null.
Then The method instance will be like following.
public function show($id = null)
{
if ($id) {
return "Showing user with ID: $id"; //returns 5
} else {
return "No ID provided — showing guest view.";
}
}
If a route has multiple parameters or $request along with optional parameter like following,
Route::post('/user/{id1}/{id2?}', [UserController::class, 'update']);
Then, while writing the controller method the optional parameter must be initialized after other parameters like following.
public function show(Request $request, $id1, $id2 = null)
{
if ($id2) {
return "Showing content when $id2 is set";
} else {
return "No $id2 provided — showing guest view.";
}
}
Here, as we can see same route and controller method can be used for different purpose, just by using optional parameter. Suppose, we want to use single route and controller method to display blog post list and a particular post. Then what we can do is like following.
Route (works for showing post list and a particular post):
Route::get('/post-list/{post?}', [PostController::class, 'display'])->name('post-list');
Then the controller method would be like,
public function display(?Post $post = null)
{
if($post)
{
return view("blade view location")->withPost($post);//returns single post view if the $post variable is set
}
else
{
return view("blade view of post list"); //returns post list
}
}
