Cover Image for Laravel Routing Parameters
163 views

Laravel Routing Parameters

The Laravel can define routes with parameters to capture values from the URL and use them in your controller actions. This allows you to create dynamic routes that handle various inputs and execute corresponding actions. Here’s how you can work with routing parameters in Laravel:

  1. Basic Route Parameters: You can define route parameters by enclosing them in curly braces {} within your route definition. For example:
PHP
 Route::get('/user/{id}', 'UserController@show');

In this example, {id} is a route parameter. When a user visits a URL like /user/123, the id parameter will capture the value 123, and it can be accessed in your controller method as an argument:

PHP
 public function show($id) {
     // Use $id to fetch user data or perform actions
 }
  1. Optional Route Parameters: You can make route parameters optional by providing a default value in your controller method:
PHP
 Route::get('/user/{name?}', 'UserController@showWithName')->where('name', '[A-Za-z]+');

Here, {name?} is an optional parameter. The where method is used to specify a regular expression pattern to restrict the parameter value. If a user visits /user/john, the name parameter will capture the value john, but if they visit /user, the name parameter will be null.

PHP
 public function showWithName($name = null) {
     // Use $name to fetch user data or perform actions
 }
  1. Named Route Parameters: You can also name your route parameters for better readability and access them using the Route facade:
PHP
 Route::get('/user/{id}', 'UserController@show')->name('user.profile');

You can generate URLs with named parameters like this:

PHP
 $url = route('user.profile', ['id' => 123]);
  1. Multiple Parameters: You can define routes with multiple parameters:
PHP
 Route::get('/product/{category}/{id}', 'ProductController@show');

In this case, you would define the corresponding controller method with the same number of parameters:

PHP
 public function show($category, $id) {
     // Use $category and $id to display product information
 }
  1. Regular Expression Constraints: You can use regular expression constraints to define the allowed format for route parameters. For example, to ensure that the id parameter consists of digits:
PHP
 Route::get('/user/{id}', 'UserController@show')->where('id', '[0-9]+');

This will only match URLs where the id parameter contains one or more digits.

Laravel’s routing system is quite flexible, allowing you to capture and use parameters in various ways to build dynamic and expressive routes for your application.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS