3 Laravel 11 Basics: Middleware

AI Bot
By AI Bot ·

Loading the Text to Speech Audio Player...

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. Laravel includes middleware for various tasks such as authentication and CSRF protection. This tutorial will cover the basics of creating and using middleware in Laravel 11.

Introduction to Middleware

Middleware can be thought of as layers that HTTP requests pass through before they reach your application. Each layer can inspect and even reject requests.

Defining Middleware

To create a new middleware, use the make:middleware Artisan command:

php artisan make:middleware EnsureTokenIsValid

This command creates a new EnsureTokenIsValid class in the app/Http/Middleware directory. Here’s an example of middleware that checks for a valid token:

namespace App\Http\Middleware;
 
use Closure;
 
class EnsureTokenIsValid
{
    public function handle($request, Closure $next)
    {
        if ($request->input('token') !== 'my-secret-token') {
            return redirect('home');
        }
 
        return $next($request);
    }
}

Registering Middleware

To register your middleware, add it to the app/Http/Kernel.php file. You can register middleware as global, group, or route middleware.

Global Middleware

Global middleware runs on every HTTP request to your application:

protected $middleware = [
    \App\Http\Middleware\EnsureTokenIsValid::class,
    // Other middleware
];

Assigning Middleware to Routes

You can also assign middleware to specific routes in your routes/web.php file:

use App\Http\Middleware\EnsureTokenIsValid;
 
Route::get('/profile', function () {
    // Your code here
})->middleware(EnsureTokenIsValid::class);

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. Here’s how to define middleware groups:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // Other middleware
    ],
 
    'api' => [
        'throttle:api',
        'bindings',
    ],
];

Learn more about Laravel middleware from the official Laravel documentation.

Conclusion

Middleware is a powerful tool for filtering HTTP requests in Laravel applications. This tutorial covered how to create, register, and use middleware in Laravel 11. For more detailed information, refer to the official Laravel documentation.

Happy coding with Laravel 11!


Discuss Your Project with Us

We're here to help with your web development needs. Schedule a call to discuss your project and how we can assist you.

Let's find the best solutions for your needs.