How to Register Middleware in Laravel 11

Sospeter Mong'are - Jun 19 - - Dev Community

Middleware is an essential component in Laravel applications, allowing you to filter HTTP requests entering your application. Whether you need to authenticate users, log requests, or enforce specific conditions, middleware provides a flexible way to handle these tasks. In this guide, we will walk through the process of creating and registering middleware in Laravel 11, along with practical examples.

Step 1: Creating Middleware

First, you need to create the middleware. Laravel provides an artisan command to streamline this process.

  1. Open your terminal.
  2. Run the following command to create a new middleware:
   php artisan make:middleware AdminMiddleware
Enter fullscreen mode Exit fullscreen mode

This command will generate a new middleware file at app/Http/Middleware/AdminMiddleware.php.

Step 2: Defining Middleware Logic

Next, you need to define the logic for your middleware. Open the newly created middleware file and add your logic.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (!auth()->check() || !auth()->user()->isAdmin()) {
            return redirect('/login');
        }

        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the AdminMiddleware checks if the user is authenticated and has admin privileges. If not, it redirects the user to the login page.

Step 3: Registering Middleware

In Laravel 11, middleware registration is done in the bootstrap/app.php file. You need to register your middleware so Laravel knows about it.

  1. Open bootstrap/app.php.
  2. Register the middleware by adding the following code:
   $app->withMiddleware(function (Middleware $middleware) {
       $middleware->alias([
           'admin' => \App\Http\Middleware\AdminMiddleware::class,
       ]);
   });
Enter fullscreen mode Exit fullscreen mode

This code registers the AdminMiddleware with an alias of admin.

Step 4: Applying Middleware to Routes

Now that your middleware is registered, you can apply it to your routes.

  1. Open routes/web.php.
  2. Apply the middleware to your routes as needed:
   use App\Http\Controllers\YourController;

   Route::get('/admin/dashboard', [YourController::class, 'dashboard'])
       ->name('admin.dashboard')
       ->middleware('admin');
Enter fullscreen mode Exit fullscreen mode

In this example, the admin middleware is applied to the /admin/dashboard route, ensuring that only users with admin privileges can access it.

Step 5: Testing Your Middleware

Finally, it's essential to test your middleware to ensure it works as expected. You can do this by:

  1. Logging in with a non-admin account and trying to access the protected route to see if you're redirected.
  2. Logging in with an admin account and ensuring you can access the route without issues.

Conclusion

In Laravel 11, registering and using middleware involves creating the middleware, defining its logic, registering it in bootstrap/app.php, and applying it to your routes. This process allows you to control the flow of HTTP requests and enforce specific conditions, making your application more robust and secure.

Happy coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .