Home > Software design >  Laravel 9 route groups with two conditions
Laravel 9 route groups with two conditions

Time:06-13

In my users table I have a field (boolean):

active

My routes currently use

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

but I want to do is to add the active so they will have to be authorised and active.

I can't seem to find the answer.

Thanks in advance!

CodePudding user response:

Add another middleware to group.

Route::middleware(['auth','active'])->group(function ()

You can implement that middleware like

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Active
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (!$request->user()->active){
            return redirect('login');
        }
        return $next($request);
    }
}

Obviously you need to register this middleware into app/Http/Kernel.php

protected $routeMiddleware = [

 ....
  'active' => \Illuminate\Auth\Middleware\Active::class,

]

I hope this help

  • Related