Create Laravel Routes Using Route Groups
Laravel allows you to choose from different types of options that will help you do your work faster and in a more efficient manner. Here, I would like to talk about the “Route Groups” that allows you to define multiple routes under a single group. For example, suppose you are working on a profile module and you want to write 7-8 routes for a profile. To do so, you can easily create a group and add all the routes under a single group. Route group is defined as Route::group. You can also pass some parameters to restrict group like middleware, and also set specific URL keyword as a prefix in which the routes will work. In addition to it, you can also define a route by using “as” to define the name of the group or route.
Read the following explanation for better understanding of Prefix and Middleware:-
Prefix – if you want the routes are only under the specific keyword mention in the Route::group.
Middleware – Middleware is used to verify the user of your application is authenticated.
The code that you need to write in web.php would look something like this:
Route::group(['prefix' => 'profile', 'as' => 'profile.','middleware' => 'auth'], function()
{
Route::get('/',['as' => 'all', 'uses' => 'ProfileController@index']);
Route::get('edit',['as' => 'edit', 'uses' => 'ProfileController@edit']);
}
You can use above route in your web.php like this:
You can also use nested groups if you define multiple middlewares for different routes. So, you can just add a group by prefix and under that, you can add another group in which you define middlewares that you want to use.
I’m sure this article helps. Share your suggestions and queries in the comment section below.
If you have any queries or doubts about this topic please feel free to contact us. We are here to help you!