Middleware in Laravel – (9 Examples) Route, Controller, Route Service Provider

best practice for Middleware in Laravel

Middleware in Laravel with 8 super examples. Apply middleware with parameters, Exclude middleware with or without group, multiple middlewares. Read detailed docs on middleware at the official Laravel website (Laravel Middleware).

  • Applying middleware group to routes
  • Applying middleware with parameters
  • Excluding specific middleware from a route
  • Excluding middleware from a group of routes
  • Applying middleware to a group of routes
  • Applying middleware directly to a route
  • Applying multiple middleware to a route

In Laravel projects, where and how do you define your middleware? Is it better to define middleware in path files or in controllers, in your opinion?

In routes

Middleware in Laravel

Example 1: Applying middleware group to routes

Route::middleware (['web'])→group (function () {
    Route::get('/profile', [ProfileController::class, 'index']);
    Route::post('/profile', [ProfileController::class, 'update']);
});
// Routes within this group will have the 'web' middleware applied
// This middleware group can include session management, CSRF protection, and more

Example 2: Applying middleware with parameters

Suppose you want to create a middleware that checks if the authenticated user has certain permissions to access a specific route. The middleware should accept parameters to specify the required permissions dynamically.

Route::get('/admin/dashboard', [HomeController::class, 'dashboard'])
→middleware('role: editor');
// This route is accessible only to users with the 'editor' role


// Breakdown this example
php artisan make:middleware CheckPermissions

// open `app/Http/Middleware`
<?php
namespace App\Http\Middleware;
use Closure;
class CheckPermissions
{
    public function handle($request, Closure $next, ...$permissions)
    {
        // Check if the authenticated user has the required permissions
        if (!$request->user()->hasAnyPermission($permissions)) {
            abort(403, 'Unauthorized');
        }

        return $next($request);
    }
}

// routes/web.php
<?php
use App\Http\Middleware\CheckPermissions;

Route::get('/dashboard', function () {
    // Your dashboard logic
})->middleware(CheckPermissions::class . ':view-dashboard');

Route::post('/admin/users', function () {
    // Create a new user logic
})->middleware(CheckPermissions::class . ':create-user');

In this example, the CheckPermissions middleware is applied to the /dashboard route and the /admin/users route. The middleware is passed a parameter specific to each route (view-dashboard and create-user, respectively).

Now, when a user tries to access the /dashboard route or create a new user at /admin/users, the middleware will check if the user has the required permission before allowing or denying access to the route.

Example 3: Excluding specific middleware from a route

Route::post('/api/data', function () {
// This route does not require the 'Ensure TokenIsValid' middleware
})→withoutMiddleware ([EnsureTokenIsValid::class]);

Example 4: Excluding middleware from a group of routes

Route:: without Middleware ([EnsureTokenIsValid::class])→group (function () {
});
// Routes within this group will not have the 'Ensure TokenIsValid' middleware applied

Example 5: Applying middleware to a group of routes

Route::middleware ([EnsureTokenIsValid::class])→group(function () {
});
// Routes within this group will have the 'Ensure TokenIsValid' middleware applied
//

Example 6: Applying middleware directly to a route

Route::get('/dashboard', function () {
// This route requires the 'Authenticate' middleware for user authentication })
→middleware (Authenticate::class);

Example 7: Applying multiple middleware to a route

Route::get('/api/data', function () {
// This route requires both the 'FirstMiddleware' and 'SecondMiddleware' to be executed 
})→middleware ([FirstMiddleware::class, Second Middleware::class]);

In Controllers

Middleware in Laravel in controllers
<?php
class UserController extends Controller
{
    {
        public function __construct()
            Example1: Applying middleware to all actions with in a controller
            $this->middleware('auth');
            // Requires user authentication for all methods in the controller

            Example2:
            Applying middleware to a specific action
            $this->middleware('log') →only('index');
            // The 'log' middleware is executed only for the 'index' method

            Example3:
            Applying middleware to all actions except specificones
            $this->middleware('subscribed') →except('store');
            // The 'subscribed' middleware is applied to all methods except 'store'

            // you can pass more than one in both only() and except()
    }
}

In Route Service Provider

app/Provider/RouteServiceProvider.php:

class RouteServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));
 
            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }
}

you can also apply middleware in Kernel.php and middleware defined in Kernel.php to be executed for every request. app/Http/Kernel.php

Similar Posts

Leave a Reply

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