Applying a simple middleware tutorial in Laravel

Muhammad Ali
Jun 6, 2023

--

Let us create middlware in laravel which will check the age and act according to it.

Step1: Create a middleware.

php artisan make:middleware CheckAge

Step 2: Define the Middleware Logic.

now goto App -> HTTP -> Middleware -> CheckAge.php and add the following code.

if ($request->age < 18)

{

return redirect(‘/home’);

}

Step 3: Register the Middleware.

in the kernal.php find the $routeMiddleware property and add there checkAge Middleware.

protected $routeMiddleware = [

// other middleware entries…

‘checkAge’ => \App\Http\Middleware\CheckAge::class,

];

Step 4: Add code in Blade File.

Code:

Output if the age is 33:

Output if the age is less then 18:

Output:

Hope this tutorial helps.

--

--