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:



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.

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


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:

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:

Create Views


Now let’s check

If the URL or or it redirects the home page.

Or if the URL redirects the age.blade.php file.