Custom Middleware in Laravel 8

Create Laravel custom middleware to check age using Laravel 8

Posted by Ervin Adams on May 4, 2021

In this tutorial you will be shown how to create a custom middleware. This example will check the user's age.

step 1. Create Middleware class by execute command

php artisan make:middleware CheckAge

Once the command is successful the file should be located at "app/Http/Middleware/CheckAge.php"

After editing the file in order to check age it looks like this:

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->input('age') < 24) {

     session()->flash('error', 'you are not of age');

     return redirect()->route('index');

}

     return $next($request);

}

}

Step 2. Register your middleware here "app/Http/Kernel.php":

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {

    ....

    /**

     * The application's route middleware.

     *

     * These middleware may be assigned to groups or used individually.

     *

     * @var array

     */

    protected $routeMiddleware = [

        ....

        'checkAge' => \App\Http\Middleware\CheckAge::class,    

    ];

}

Step 3. Create CheckAge Controller by executing command:

php artisan make:controller CheckAgeController

"app/Http/Controller/CheckAgeController"

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CheckAgeController extends Controller {

    public function index()     {

        return view("age-checker");

    }

}

Step 4. Create Home Controller by executing command:

php artisan make:controller HomeController

"app/Http/Controller/HomeController"

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller {

    public function index()     {

        return view("home");

    }

}

Step 5. Create view check:

1.53 KB
   
<!DOCTYPE html>
<head>
    <meta charset="utf-8">

    <title>Wikicode custom middleware tutorial</title>

    <meta name="description" content="Wikicode check age using custom middleware in Laravel 8">
    <meta name="author" content="Wikicodes">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<html>
<body>
<div class="container align-items-start">
    @if (session('error'))
        <div class="alert alert-danger mt-3">
            {{ session('error') }}
        </div>
    @endif
    <div class="container-fluid d-flex justify-content-center" style="max-width: 30em">
        <form id="signin" class="form-horizontal validate-form" method="POST" action="{{ route('check.age') }}">
            {{ csrf_field() }}

            <div class="form-group">
                <label for="age" class="control-label">Age</label>
                <input id="age" type="text" class="form-control @error('email') is-invalid @enderror" name="age" value="{{ old('age') }}">
                @error('age')
                <div class="error-txt">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group mb-0">
                <button type="submit" class="btn btn-primary">
                    checkage
                </button>
            </div>
        </form>
    </div>
</div>
</body>
</html>


Step 6. Create view home:

"resources/views/home.blade.php"

<h1>I am home!!!<h1>

Step 7. Create Routes

"routes/web"

use App\Http\Controllers\CheckAgeController;

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::middleware(['guest'])->group(function(){

    Route::get('/', [CheckAgeController::class, 'index'])->name('index');

});

Route::middleware(['checkAge'])->group(function(){

    Route::post('/check-age', [CheckAgeController::class, 'checkAge'])->name('check.age');

    Route::get('/home', [HomeController::class, 'index'])->name('home');

});

Step 8. Now start server

php artisan serve --port 3000

Enter a number less than and then greater than 24 to see the middleware in action 

 If you wish to download this tutorial go to https://github.com/wecode101/custom_middleware_laravel_8