2015-03-13 108 views
1

我想知道是否有更好的方式来处理我的身份验证用户在不同类型的用户方面的方式。在Laravel 5中有两种类型的用户

我有一个基本的用户和一个管理员用户。基本用户显然只能访问基本页面,管理员用户需要访问基本用户无法访问的其他页面。

我一直在做的事情是:我创建了我的表中的列SUPER_USER并添加:

if(Auth::user()->super_user == 0) { 
     return Redirect::to('/')->with('error', 'You do not have permission to access this page'); 
    } 

到,我不希望有一个基本的用户能够访问的每个页面。现在,这工作,但我开始将我的应用程序转换到Laravel 5,我想有一种不同的方式可以处理这个问题。

+0

@Lunx如果你满意我的回答如下,接受它:) – 2015-03-20 13:04:28

+0

对此深感抱歉队友!这实际上工作,我能够用你的指导来解决我的问题! – Lynx 2015-03-21 03:26:44

回答

3

处理用户角色的最佳方法是使用Middleware

  1. 创建中间件:
namespace App\Http\Middleware; 

use Closure; 
use Illuminate\Contracts\Auth\Guard; 

class Admin 
{ 
    /** 
    * The Guard implementation. 
    * 
    * @var Guard 
    */ 
    protected $auth; 

    /** 
    * Create a new filter instance. 
    * 
    * @param Guard $auth 
    * @return void 
    */ 
    public function __construct(Guard $auth) 
    { 
     $this->auth = $auth; 
    } 

    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     if (!$this->auth->getUser()->super_user) { 
      return redirect->to('/') 
       ->with('error', 'You do not have permission to access this page'); 
      } 
     } 

     return $next($request); 
    } 
} 
  • 它添加到app\Http\Kernel.php
  • protected $routeMiddleware = [ 
        'admin' => 'App\Http\Middleware\Admin', 
    ]; 
    
  • 使用middl eware在您的路线:
  • Route::group(['middleware' => ['admin']], function() { 
        // your route 
    });