2016-02-11 69 views
1

在我的應用程序中,我使用默認認證將我的用戶登錄到他們的儀表板。 現在我想爲支持者和管理員創建一個後端。 我用這個代碼,此刻以管理員身份登錄:laravel5.1手動認證用戶

<?php 

namespace App\Http\Controllers\Admin; 

use Illuminate\Http\Request; 
use App\Http\Requests; 
use App\Http\Controllers\Controller; 
use App; 
use Artisan; 
use Validator; 
use Auth; 

class AdminLoginController extends Controller 
{ 

    public function index() 
    { 
     return view('admin.login'); 

    } 

    public function authenticate(Request $request) 
    { 
     if (Auth::attempt(['username' => $request->username, 'password' => $request->password, 'id' => 1])) 
     { 
      // Authentication passed... 
      dd("correct"); 
     } 
     else 
     { 
      dd("login data incorrect!"); 

     } 
    } 

} 

我怎麼能現在使用登錄後的衆所周知的重定向。 在我AuthController我使用的用戶我用這個代碼:

/** 
* Where to redirect users after login/registration. 
* 
* @var string 
*/ 
protected $redirectTo = '/dashboard'; 
protected $redirectAfterLogout = 'auth/login'; 
protected $redirectPath = '/dashboard'; 

1)我怎麼能在我上面的代碼中使用此?我想重新定向管理員登錄到應用程序像用戶使用此laravel功能指定的網址。

2.)在if語句中檢查更多「id」的最佳方法是什麼?因爲會有多個管理員。

+0

請解釋一下,你能否成功地匹配用戶信息?第二,爲什麼你不使用laravel的基於角色的包,例如:'https:// github.com/Zizaco/entrust' 3rd,而不是通過'id'將用戶表中的'user_type'字段放在用戶表中。並檢查登錄 – Qazi

回答

1

首先你要檢查用戶名,密碼和ID。所以只有Id = 1的用戶纔會被你的函數認證。你不需要在那裏放一個ID檢查。

現在重定向,你可以做一個函數,根據用戶類型返回url。這是一個非常基本的example`

public function getRedirectUrl(){ 
    if(auth()->user()->isAdmin()){ 
     return url('/admin-dashboard'); 
    } 
    elseif(auth()->user()->isUser()){ 
    return url('/user-dashboard') 
    } 
} 

請確保您有isAdmin()和isUser()在您的用戶模型中定義的一樣

public function isAdmin(){ 
    return $this->user_type == UserType::ADMIN; 
} 

所以在您的身份驗證功能功能只是做return redirect($this->getRedirectUrl())

+0

非常感謝,但如何檢查isAdmin()函數,檢查,如果用戶ID匹配一個ID數組?使用ID來檢查管理員權限對我來說是更好的解決方案。 –

+0

想一想,說你的應用程序現在有10000個用戶。你將如何跟蹤管理員的身份,爲客戶? 您需要根據另一列對用戶進行分組。說user_type_id。然後給你所有的管理員的值10,用戶值爲1.然後在isAdmin()你可以簡單地檢查$ this-> user_type_id == 10; – themightysapien