0
0
Laravelframework~15 mins

Optional parameters in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Laravel Route Optional Parameters
📖 Scenario: You are building a simple Laravel web app that greets users. Sometimes users provide their name, and sometimes they don't. You want to create a route that can handle both cases gracefully.
🎯 Goal: Create a Laravel route with an optional parameter name. If the name is provided in the URL, the app should greet the user by name. If not, it should greet with a default message.
📋 What You'll Learn
Create a route with an optional parameter {name?}
Set a default value for the optional parameter inside the route callback
Return a greeting message that uses the name parameter if given
Return a default greeting message if name is not provided
💡 Why This Matters
🌍 Real World
Optional parameters in routes let web apps handle URLs with or without extra info, like user names or IDs, making navigation smoother.
💼 Career
Understanding optional route parameters is essential for Laravel developers to build flexible and user-friendly web applications.
Progress0 / 4 steps
1
Create a basic route
Create a Laravel route using Route::get for the URL path /greet that returns the string 'Hello, Guest!'.
Laravel
Need a hint?

This route responds to /greet with a simple greeting.

2
Add an optional parameter
Modify the route path to include an optional parameter called {name?} after /greet.
Laravel
Need a hint?

Optional parameters have a question mark ? after the name inside curly braces.

3
Add a parameter to the callback
Add a parameter called $name to the route callback function and set its default value to 'Guest'.
Laravel
Need a hint?

Set the default value for $name in the function parameter list.

4
Use the parameter in the greeting
Change the return statement to use the $name parameter in the greeting message using string interpolation: "Hello, $name!".
Laravel
Need a hint?

Use double quotes to include the variable $name inside the string.