Laravel Route Parameters

Laravel Route Parameters

Required Parameters:

We need to capture segments of the URI within our route.

We are going to see how to pass parameters through two or many views inside the closure function.

Output:

Laravel Route Parameters 1
Laravel Route Parameters 2
Laravel Route Parameters 3

We need to capture a users id from the URL.

We do so by defining route parameters.

E.g.:

Output:

Laravel Route Parameters 4

In the above example, we can see how to pass the variable to the closure function.

We define as many route parameters as required by our route:

E.g.:

Output:

Laravel Route Parameters 5

In the above example, the 50 is represented as an ( id ), the Rafia describes as a ( name ).

Route parameters are always enclosed within { } braces, and it should consist of any alphabetic characters. It may not contain a character. Instead of using the character, we use an underscore (_). Route parameters are placed into route callbacks/controllers based on their order the names of the callback/controller arguments do not matter.

Optional Parameters

We need to specify route parameters occasionally, but we make the presence of route parameter route. We can place a (?) mark after the parameter name.

We make sure to give the routes corresponding variable a default value.

Regular Expression Constraints

We may constrain the format of our route parameters using the where method.

The where method obtain the name of the parameters and a regular expression defining the parameter that should be constrained:

Global Constraints

We would like a route parameter to always be constrained by a given regular expression, we can use the pattern method. We can define these patterns in the boot method of ours RouteServiceMethod.

Once the pattern has been defined, it will be automatically applied to all the outers using the parameter name:

Encoded Forward Slashes

The Laravel routing component allows all the characters except /. We must explicitly allow / to be part of our placeholder using a where condition regular expression.