What Are The Route Groups In Laravel Framework With Example

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method. Nested groups attempt to intelligently "merge" attributes with their parent group. Middleware and where conditions are merged while names, namespaces, and prefixes are appended. Namespace delimiters and slashes in URI prefixes are automatically added where appropriate.

What Are The Route Groups In Laravel Framework With Example

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.

 

Route::group( [ ] , callback); 
 

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

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.

 

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.

Example(1)

web.php

Route::group(['prefix' => 'test'], function()
{
    Route::get('/test_one',function()
    {
        echo "test1 tutorial";
    });
    Route::get('/test_two',function()
    {
        echo "test2 tutorial";
    });
    Route::get('/test_three',function()
    {
        echo "test3 tutorial";
    });
});
 

Middleware

To assign middleware to all routes within a group, you may use the middleware method before defining the group. Middleware are executed in the order they are listed in the array:

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second Middleware
    });

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
});


Example(1)
Open app\Http\kernel.php and add below code that to that file

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
  
    protected $routeMiddleware = [
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
        ];
}


Implement code in AdminMiddleware.php in app\Http\Middleware folder

<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        {

    //return "middleware";
            echo "Hello World welcome to Bajarangisoft <br>";
            return $next($request);

        }
    }
}


Create routes in web.php

//admin Lead Accessible Routes
Route::middleware(['auth','admin'])->group(function(){

    Route::get('/test_one',function()
    {
        echo "test1 tutorial";
    });
    Route::get('/test_two',function()
    {
        echo "test2 tutorial";
    });
    Route::get('/test_three',function()
    {
        echo "test3 tutorial";
    });
});

after you create like above example pass url in google chrome( http://localhost/laraveldemoproject/test_one) you get login page without login to username and password you wont get specified route data when you create middleware.

Namespaces

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace method:

Route::namespace('Admin')->group(function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});


Remember, by default, the RouteServiceProvider includes your route files within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers namespace prefix. So, you only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace.

Subdomain Routing

Route groups may also be used to handle subdomain routing. Subdomains may be assigned route parameters just like route URIs, allowing you to capture a portion of the subdomain for usage in your route or controller. The subdomain may be specified by calling the domain method before defining the group:

Route::domain('{account}.myapp.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});

In order to ensure your subdomain routes are reachable, you should register subdomain routes before registering root domain routes. This will prevent root domain routes from overwriting subdomain routes which have the same URI path.

Route Prefixes

The prefix method may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin:

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        // Matches The "/admin/users" URL
    });
});


Route Name Prefixes

The name method may be used to prefix each route name in the group with a given string. For example, you may want to prefix all of the grouped route's names with admin. The given string is prefixed to the route name exactly as it is specified, so we will be sure to provide the trailing . character in the prefix:
 

Route::name('admin.')->group(function () {
    Route::get('users', function () {
        // Route assigned name "admin.users"...
    })->name('users');
});

Related Post