create middleware in laravel

732 0 0 0

Last Updated : 2024-03-29 09:02:16

this snippet will teach you how to create a middleware for accessing specific routes , for example is to test if admin is logged in or not

1- run this php artisan


php artisan make:middleware IsAdmin

2-  Add it to the routeMiddleware array in your kernel file by opening app/Http/Kernel.php


'isAdmin' => \App\Http\Middleware\IsAdmin::class,

3- Edit isAdmin middleware file:


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class IsAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (Auth::guard('admin')->check()) {
return $next($request);
} else {
return abort(404);
}
}
}

4- Apply the middleware to your route:


Route::prefix('admin')->middleware('isAdmin')->as('admin.')->group(function () {
// your routes here
});

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.