Laravel route parameter

Created at 20-Feb-2022 , By samar

Laravel route parameter

In this tutorial, we will try to find the solution to "Laravel route parameter" through programming.

Sometimes, you have to capture segments of the URI from the URL. You may do so by defining route parameters. You can pass parameters in the Laravel route in two different ways. First we can pass parameters as required and second we can pass them as optional in Laravel.
  • Laravel route with required parameter

    --PATH routes\web.php
    Route::get('/user/{id}', function ($id) {
        return 'User '.$id;
    });
    

    Visit http://localhost:8000/user/1 to get the output. Here we create a route with the required parameter (id) which is returned by the callback function as the output. It will return the error if we did not pass the parameter value while visiting the URL.

  • Laravel route with optional parameter

    --PATH routes\web.php
    Route::get('/user/{name?}', function ($name = 'John') {
        return $name;
    });
    

    Visit http://localhost:8000/user/samar to get the output. Here we create a route with the optional parameter (name) which is returned by the callback function if we pass it as a URI segment else it will return john as output which is default value.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.