Laravel route parameter

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.

Answers 2
  • Laravel route with required parameter

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

    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;
    });
    
    0

    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