简体   繁体   中英

How to use laravel Multiple Auth Guard for same controller

laravel 5.2

I have and multiple auth Gard given below

Admin
Clients
Employee

i have

    
ItemController
        ->index.blade.php
        ->create.blade.php
        ->edit.blade.php

ItemKitController
        ->index.blade.php
        ->create.blade.php
        ->edit.blade.php

I want to use Client and Employee Guard to access same Controller and view mention above.

is their any possible way.

maybe you want something like this

public function __construct()
    {
        $this->middleware('auth:Admin,Clients,Employee');
    }

in your controller

You can use middleware like:

Route::group([ 'middleware' => ['Admin', 'Clients', 'Employee'] ], function(){
  Route::get('/Admin', 'AdminController@index');
  Route::get('/Clients', 'ClientsController@index');
  Route::get('/Employee', 'EmployeeController@index');

});

For instance, I have an admin middleware that checks if user id is 1

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Log;

class AuthAdmin
{
    private $admins; // Admin ids

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->admins = config('custom.admins'); // get configs
        $user = Auth::user();

        if($user->id != 1)){
            // not admin, redirect home
            return redirect('/');
        }

      // is admin, let request continue
      return $next($request);
    }
}

Then you have to add it to Kernel.php "$routeMiddleware":

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        // Custom Middleware
        // Auth Admin
        'auth_admin' => \App\Http\Middleware\AuthAdmin::class,
    ];

Then in my routes:

Route::group([ 'middleware' => ['auth_admin'] ], function(){

    // nobody can come to these routes but admins
    Route::get('/admin/index', 'AdminController@index');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM