Javatpoint Logo
Javatpoint Logo

Route Groups

Route Groups is an essential feature in Laravel, which allows you to group all the routes. Routes Groups are beneficial when you want to apply the attributes to all the routes. If you use route groups, you do not have to apply the attributes individually to each route; this avoids duplication. It allows you to share the attributes such as middleware or namespaces, without defining these attributes on each individual route. These shared attributes can be passed in an array format as the first parameter to the Route::group method.

Syntax of Route Group

Parameters

[ ]: It is an array passed to the group method as a first parameter.

Example of Route Groups

web.php

In the above code, we define the group() method, which contains the two parameters, i.e., array and closure. Inside the closure, we can define the routes as many as we want. In the above code, we define three routes.

Output:

When we access the URL "localhost/laravelproject/public/first", then the output would be:

Laravel Route Groups

When we access the URL "localhost/laravelproject/public/second", then the output would be:

Laravel Route Groups

When we access the URL "localhost/laravelproject/public/third", then the output would be:

Laravel Route Groups

Path Prefixes

Path prefixes are used when we want to provide a common URL structure.

We can specify the prefix for all the routes defined within the group by using the prefix array option in the route group.

Let's understand through an example.

web.php

The above code contains three routes which can be accessed by the following URLs:

/tutorial/aws

Laravel Route Groups

/tutorial/jira

Laravel Route Groups

/tutorial/testng

Laravel Route Groups

Middleware

We can also assign middleware to all the routes within a group. Middleware can be defined before creating the group by using the middleware method.

Let's understand through an example.

web.php

CheckAge.php (middleware)

Output:

Laravel Route Groups
Laravel Route Groups
Laravel Route Groups

Route Name Prefixes

The name method is used to prefix each route name with some specified string. In the name method, we need to specify the string with a trailing character in the prefix.

Let's see an example.

web.php

In the above code, the name of the route would be admin.users.






Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA