How to create Middleware in Laravel

Middleware is a mechanism that allows you to filter HTTP requests entering your application. It sits between your application and the user’s browser, intercepting incoming requests and performing actions before passing the request on to the application’s routes or controllers. Middleware is useful for tasks such as authentication, logging, and input validation.

Laravel provides several middlewares out of the box, such as the auth middleware for authentication, the csrf middleware for protecting against cross-site request forgery attacks, and the throttle middleware for rate limiting.

To use a middleware, you can either apply it to individual routes in your routes/web.php file, or apply it globally to all routes by adding it to the $middleware array in your app/Http/Kernel.php file.

Step 1: Open the Terminal

Open your terminal or command line and navigate to your Laravel project directory.

Step 2: Create a middleware file

Use the make:middleware Artisan command to generate a new middleware class. For example, to create a middleware called CheckAgeMiddleware, run the following command.

php artisan make:middleware CheckAgeMiddleware

This will create a new file called CheckAgeMiddleware.php in the app/Http/Middleware directory.

Step 3: Modify a middleware file

Open the CheckAgeMiddleware.php file and modify the handle method to add your middleware logic. This method takes two parameters: $request and $next. The $request parameter contains the HTTP request object, while the $next parameter is a closure that represents the next middleware in the chain. You can modify the request object, or return a response object to stop the middleware chain.

Here’s an example of a CheckAgeMiddleware that checks if the user is over 18 years old.

namespace App\Http\Middleware;
use Closure;

class CheckAgeMiddleware
{
    public function handle($request, Closure $next)
    {
        $age = $request->input('age');

        if ($age < 18) {
            return response('You must be over 18 to access this page.', 403);
        }

        return $next($request);
    }
}

Step 4: Register Middleware

Register your middleware in the app/Http/Kernel.php file. This file contains an array of middleware groups, each with its own set of middleware classes. You can add your middleware to an existing group, or create a new group.

To add your middleware to an existing group, find the group in the $middlewareGroups property, and add your middleware class to the array.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,

        // Add your middleware here
        \App\Http\Middleware\CheckAgeMiddleware::class,
    ],

    // ...
];

To create a new middleware group, add a new key-value pair to the $middlewareGroups array.

protected $middlewareGroups = [
    'web' => [
        // ...
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,

        // Add your middleware here
        \App\Http\Middleware\CheckApiKeyMiddleware::class,
    ],
];

Step 5: Add Middleware in Route

Use your middleware in a route or controller. To use your middleware in a route, you can add it to the route definition.

Route::get('/dashboard', function () {
    // ...
})->middleware('checkage');

To use your middleware in a controller, you can add it to the constructor or to a specific method.

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('checkage');
    }

    public function index()
    {
        // ...
    }
}

You can set middleware in route either in the controller.

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

Leave a Reply

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