How to create a middleware in Laravel?

Photo by JOHN TOWNER on Unsplash

How to create a middleware in Laravel?

Creating middleware in Laravel is a common task that helps to filter HTTP requests entering your application. Middleware can perform various tasks such as authentication, logging, and modifying request/response objects.

Step 1: Create Middleware

You can create middleware using the Artisan command-line tool. Open your terminal and run the following command:

php artisan make:middleware CheckAge

This will create a new middleware class named CheckAge in the app/Http/Middleware directory.

Step 2: Define Middleware Logic

Open the newly created middleware file (app/Http/Middleware/CheckAge.php) and define the logic you want to apply. For example, you might want to check if the user is above a certain age:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAge
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->age <= 18) {
            return redirect('home');
        }

        return $next($request);
    }
}

In this example, the middleware checks if the age parameter in the request is less than or equal to 18. If so, it redirects the user to the home route. Otherwise, it allows the request to proceed further.

Step 3: Register Middleware

You need to register your middleware in the app/Http/Kernel.php file. Middleware can be registered globally, assigned to specific routes, or grouped.

Registering Globally

To apply middleware to every request globally, add it to the $middleware array in the app/Http/Kernel.php file:

protected $middleware = [
    // ...
    \App\Http\Middleware\CheckAge::class,
];

Registering as Route Middleware

If you want to use the middleware on specific routes, add it to the $routeMiddleware array:

protected $routeMiddleware = [
    // ...
    'check.age' => \App\Http/Middleware\CheckAge::class,
];

Step 4: Use Middleware in Routes

Once the middleware is registered, you can use it in your routes or controllers. Open the routes/web.php file and apply the middleware to specific routes:

Route::get('profile', function () {
    // Only users older than 18 can access this route
})->middleware('check.age');

Or apply it to a group of routes:

Route::group(['middleware' => ['check.age']], function () {
    Route::get('profile', function () {
        // Only users older than 18 can access this route
    });

    Route::get('settings', function () {
        // Only users older than 18 can access this route
    });
});

Step 5: Testing Middleware

You should test your middleware to ensure it works as expected. Create test cases or manually test different scenarios to verify the middleware's behavior.

Example Test Scenario

To manually test, you can use a URL with different age query parameters to see if the redirection works:

httpCopy codehttp://your-app.test/profile?age=17  // This should redirect to 'home'
http://your-app.test/profile?age=19  // This should allow access to 'profile'