2015-10-26 141 views
1

我使用的是Laravel 5.1和Laravel的默认身份验证系统。带条件的Laravel身份验证

在数据库(MySQL)中添加一个名为'role'的新列。对于管理员而言,值为1,对于成员则为2。

现在我只想为管理员授予登录权限,表示值为1的情况。我该怎么做?

+0

所以,只是为了澄清,你想管理员能做什么?授予登录权限听起来像你只希望管理员能够登录到您的网站 – James

+0

是的我只想要管理员可以登录。 – smartrahat

+0

好的,但是如果他们无法登录,允许会员注册,那有什么意义?或者您是否只想将部分网站限制为管理员? – James

回答

1

其实我解决它。我只是将这些代码加入postLogin()方法的AthenticatesUsers.php方法中。

// If role is equal to 1, user allowed to login 
    // You can change $admin value anytime according to database Design 
    // Example: In role column the value for admin is 2 or A. You just need to change the value of $admin. 
    $userData = User::select('role')->where('email',$request['email'])->first(); 
    $admin = 1; 
    $role = $userData->role; 
    if($role == $admin){ 
     $request['role'] = $role; 
    } 
0

我觉得有更好的方法可以实现你的目标,比如middleware,但是考虑到你之后会是这样做的一种方式。

登录用户后,我们发送到“家”,除非您在AuthController中另有指定。

routes.php里面,如果你只是建立一个GET路径指向一个HomeController(或任何你的名字),那么你可以使用一个函数来运行你以后的测试。

routes.php文件

Route::get('home', '[email protected]');

的HomeController

public function index() 
    { 
     //If they are yet to log in then return your normal homepage 
     if (Auth::guest()) 
     { 
      return View::make('home'); 
     } 
     else 
     { 
      //Run your tests here to check their role and direct appropriately 
      //Given you have added the role column to the users table, you can access it like so: 
      //Auth::user()->role 
     } 
    }