popolo - code simple..

popolo - code simple..

Laravel Middleware to auth admin users

Laravel Middleware to auth admin users

Theodoros Kafantaris's photo
Theodoros Kafantaris
·Sep 20, 2022·

1 min read

In this post we will see how to authenticate users that have a DB field of is_admin to separate them from normal users. In users migration file we have the boolean extra field to characterise a user as admin.

Schema::create('users', function (Blueprint $table) {

Now we are ready to create our custom middleware.

php artisan make:middleware isAdmin

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

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::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' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'admin' => \App\Http\Middleware\IsAdmin::class,

We are modifying the app/Http/Middleware/isAdmin.php file as follow:

public function handle(Request $request, Closure $next)
        if (auth()->user() &&  auth()->user()->is_admin == 1) {
            return $next($request);
     abort(403, "You are not authorised");
    // return redirect('/');

Apply the middleware to web.php:

Route::middleware(['auth','admin'])->group(function () {
    Route::get('/dashboard', function () {
   return view('dashboard');

That's it! Enjoy!

Share this