2015-10-26 96 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 
     } 
    }