Simple Uses of Laravel 8/9 Routes Group

This tutorial help to understand Laravel 8/9 group with example. We will create a route group in Laravel 8, bind 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( [ ] , callback);

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 allow 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 a namespace into Laravel using the 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 –

// EmpController.php
public function index()
{
  return 'Welcome!! Admin namespace';
}

Now, We’ll define group routes and use namespace :

// web.php
Route::group(['namespace' => 'Admin'], function() {
 Route::resource('emps', 'EmpController');
});

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.

// web.php
Route::group(['namespace' => 'Admin', 'prefix' => 'admin'], function() {
  Route::resource('emps', 'EmpController');
});

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.

// web.php
Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'auth'], function() {
  Route::resource('emps', 'EmpController');
});

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

Leave a Reply

Your email address will not be published.