Multiple auth for laravel

I want to split the middleware into two roles for the administrator, and the second for the user but some route is used for all users and administrators, and several routes for the administrator - just how can I split the route?

Auth::routes();
Route::group(['middleware' => 'auth'], function () {        
     //Some route here 
});

Route::group(['middleware' => ['guest']], function () {
   //some route here
});
+4
source share
1 answer

Here is my implementation for access control for the administrator and users (agents in my case). I have a boolean field in my user table ( is_admin) which is 0 for regular users and 1 for admins.

In your user model, add the following:

protected $casts = [
    'is_admin' => 'boolean',
];

public function isAdmin()
{
    return $this->is_admin;
}

Create new intermediaries for the administrator and agent:

php artisan make:middleware Admin

php artisan make:middleware Agent

Middleware files will be created in App\Http\Middleware\

Admin.php:

public function handle($request, Closure $next)
{
    if ( Auth::check() && Auth::user()->isAdmin() )
    {
        return $next($request);
    }
    return redirect('/agent');
}

Agent.php

public function handle($request, Closure $next)
{    
    if ( Auth::check() && !Auth::user()->isAdmin() )
    {
        return $next($request);
    }    
    return redirect('/home');
}

laravel, protected $routeMiddleware Kernel.php, app\Http\Kernel.php

'admin' => 'App\Http\Middleware\Admin',
'agent' => 'App\Http\Middleware\Agent',

, . . , , , .

admin:

    public function __construct()
{   

    $this->middleware('auth');
    $this->middleware('admin');
}

() :

public function __construct() {

$this->middleware('auth');
$this->middleware('agent');

}

,

Route::group(['middleware' => 'admin'], function () {        
     //Some route here 
});
+3

Source: https://habr.com/ru/post/1693309/


All Articles