Understanding Laravel Route with Optional Parameter

Provision:

You must already understand about Route Parameter

 

Definition

In Browser : Optional Parameter is a parameter that can be included or not in URI

In Laravel Route Configuration : Optional parameter is a character of ? after parameter name

 

Purpose

To give default value if parameter not inserted in URI so the page not showing error 404

 

Example

I have this localhost URL

http://localhost:8000/trending_now/13

Known:

Number 13 in above URI is trending id

The browser result is like this
laravel_optional_param2

Wanted:

I want to give default value for trending id, so if trending id not included in URI then the page not show Error 404

Question:

How to do it … ?

Answer:

Open routes/web.php file and add this code:

Route::get(‘trending_now/{id_trend?}’,function($id=7) {

echo ‘ID trending is ‘.$id;

});

Explain:

  • {id_trend?} is optional parameter
  • function($id=7) is used to get the  parameter id_trend and give the value to $id variable  and if id_trend parameter  not exist in URI then this function give value 7 to $id variable

Result:

If  i not mention the trending id in URI then the page showing default value:

laravel_optional_param

 

Thanks For Reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *