0
0
Laravelframework~5 mins

Optional parameters in Laravel

Choose your learning style9 modes available
Introduction

Optional parameters let you make parts of your function or route flexible. You can call them with or without those extra details.

When you want a route to work with or without extra information, like a user ID.
When a function can do a default action if no special input is given.
When you want to keep your code simple but still handle different cases.
When you want to avoid errors if some data is missing in a request.
Syntax
Laravel
public function example($required, $optional = null) {
    // code here
}

Route::get('/user/{id?}', function ($id = null) {
    // code here
});

Optional parameters must come after required ones.

Use = null or a default value to make a parameter optional.

Examples
This function says hello to a name or to 'Guest' if no name is given.
Laravel
public function greet($name = 'Guest') {
    return "Hello, $name!";
}
This route shows a post if an ID is given, or all posts if not.
Laravel
Route::get('/post/{id?}', function ($id = null) {
    if ($id) {
        return "Post ID: $id";
    } else {
        return "All posts";
    }
});
Sample Program

This Laravel route welcomes a user by name if provided. If no name is given, it uses 'Friend' as a default.

Laravel
<?php

use Illuminate\Support\Facades\Route;

Route::get('/welcome/{name?}', function ($name = 'Friend') {
    return "Welcome, $name!";
});
OutputSuccess
Important Notes

Always put optional parameters at the end to avoid confusion.

In routes, use a question mark ? after the parameter name to mark it optional.

Set a default value in the function to handle missing parameters smoothly.

Summary

Optional parameters let functions and routes work with or without extra info.

They must come after required parameters and have default values.

Use them to make your Laravel code flexible and user-friendly.