Middleware example in laravel

hello artisan, Today we will learn all about middleware. In this example, we will learn how to middleware works. Middleware in laravel is very easy to implement. So, let’s start.

Middleware offers a simple method for reviewing and filtering HTTP requests that reach your application.

Create a middleware

php artisan make:middleware CheckAge

CheckAge is the middleware name. It can be anything if you wish to keep it. CheckAge middleware is created in the following path:

App\Http\Middleware

App\Http\Middleware\CheckAge.php

Read also: Create Laravel 8 Auto Load More Data On Page Scroll with AJAX

Register middleware

After creating a middleware, we have to register it to the kernel.php file.

App\Http\kernel.php
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'check' => \App\Http\Middleware\CheckAge::class,

];

The last one is registered by check name. It can be anything!

Create Routes

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::get('/age',function (){
    return view('age');
})->middleware('check'); // add check middleware

Route::get('/', function () {
    return view('welcome');
});

App\Http\Middleware\CheckAge.php look like:
<?php

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('/');
        }
        return $next($request);
    }
}

Here, we get the age value from the getMapping url and make a condition. If age is less than or equal 18 the url redirect to the home page.

The url looks like:

http://127.0.0.1:8000/age?age=some_value

Create Views

age.blade.php

Now let’s check

If the URL http://127.0.0.1:8000/ or http://127.0.0.1:8000/age or http://127.0.0.1:8000/age?age=15 it redirects the home page.

Or if the URL http://127.0.0.1:8000/age?age=20 redirects the age.blade.php file.