如何在同一个控制器上使用laravel Multiple Auth Guard

时间:2016-07-31 15:23:25

标签: php laravel laravel-5.2

laravel 5.2

我有以下多个auth Gard


Admin
Clients
Employee

我有

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

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

我想使用Client和Employee Guard来访问相同的Controller并查看上面提到的内容。

是他们任何可行的方式。

2 个答案:

答案 0 :(得分:3)

也许你想要这样的东西

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

答案 1 :(得分:0)

您可以使用以下中间件:

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

});

例如,我有一个管理中间件,用于检查用户ID是否为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);
    }
}

然后你必须把它添加到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,
    ];

然后在我的路线中:

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

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