Simple Uses of Laravel 8 Routes Group

This tutorial help to understand Laravel 8 group with example. We will create a route group in Laravel 8, bind the similar type of routes into a group. We can also define routes prefix and apply middleware. Routes Groups are helpful in the situation when you want to apply one attribute to all the routes.

Laravel 8 Routes Group

Route groups allow you to share route attributes, such as middleware, prefixed, or namespaces without defining these attributes on each individual route.

Syntax

Route group takes an array that can take attributes and callback function. The shared attributes can be passed in the array format as the first argument to the Route::group() function. The callback method as a second attribute.

You can read other Laravel tutorials :

Laravel 8 Route Group on namespace

Laravel namespaces allows you to partition code into logical groups by defining them into their own namespace.

The Namespace basically group your functions, classes and constants under a particular 'name'. Its a php core feature.

You can create namespace into Laravel using below command:-
php artisan make:controller Admin/EmpController --resource --model=Employee

EmpController will be created inside the Admin directory inside the app >> Http >> Controllers folder.

Let’s define index() method into the EmpController.php file –

Now, We ll define group routes and use namespace :

We have defined the Admin namespace as a first parameter and call method as a second. Save the file and go to the

http://localhost:8000/emps.

You will see :

Welcome!! Admin namespace.

Laravel Group 8 Path Prefix

You can also define the group api prefix, You can create a common prefix admin for all of your routes under admin functionality.

Now, your URL should be http://localhost:8000/admin/emps

Laravel Group Middleware

We can also defined the middleware on the routes group. The middleware help to filter the request based on your middleware logic. You can get more information about route middleware from Basic Authentication In Laravel 5 Using Middleware.

We will add auth middleware on admin routes. Let’s add the following code inside the web.php file.

Now, when the user will access above group routes, they need to validate user, Once user successfully authenticated then he will access routes functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.