2016-07-04 64 views
0

我試圖建立一個網上商店網站使用laravel框架兩個用戶身份驗證在一個表中laravel 5.2

我有這些列的表:id, username, password, division_id

其中division_id指稱爲表division有:id, division_type

和我有兩個division typeAdminCustomers

我試圖根據訪問權限訪問一定數量的頁面,例如管理員可以訪問管理員面板但不訪問客戶,客戶可以訪問客戶面板,例如產品訂單頁面,但不訪問管理員。

這兩種類型都可以在他們可訪問的頁面中做幾乎所有的事情,而我的主頁將有一個管理面板,一個客戶面板和主網站。

我該如何在我的項目中只使用一個表和中間件組?

P.S.我是新來的這個論壇

+0

什麼是關係情景? 1個用戶只屬於一個分區?或1個用戶屬於多少? –

+0

一個用戶屬於一個部門,一個部門擁有多個用戶。 – Orange

+0

正確的方法應該有兩個中間件集團路線,爲管理員和客戶 – xmhafiz

回答

0

對於這個中間件,你只需要檢查division查看站點所需要的是否與用戶所屬的division相同。在handle功能,你可以通過它表示一個部門名稱的第三個參數,如customer

當您添加中間件到你的路線,你可以通過師的名字作爲參數傳遞給handle功能,像這樣:

'middleware' => ['division:customer'] 

這在Route Group實現可能看起來是這樣的:

Route::group(['prefix' => 'customer', 'middleware' => ['division:customer']], funtion(){ 
    //route definitions for all these routes will require a "division" type of "customer" 
}); 

或者你可以把它應用到路由資源RESTful路由:

Route::resource('customer', 'CustomerController')->middleware(['divison:customer']); 

或者您也可以將其應用到具體路線:

Route::get('customer/{id}', '[email protected]')->middleware(['division:customer']); 

在你handle功能,您可以訪問該值作爲第三個參數:

public function handle($request, Closure $next, Division $division) 

要通過主鍵以外的其他方式自動解決依賴關係的過程,我們將繼續並打開我們的App\Providers\RouteServiceProvider並在boot函數中添加一些魔力。現在

public function boot(Router $router) 
{ 
    parent::boot($router); 

    $router->bind('division', function($value) { 
     return Division::where(function($query) use($value){ 
      if (is_int($value)) { 
       return $query->where('id', $value)->first(); 
      } else { 
       return $query->where('type', ucfirst($value))->first(); 
      } 

      return null; 
     }); 
    }); 

,回中間件,我們可以很容易地針對我們的handle功能$division,我們authorized用戶的比較。

if(app()->user()->division->type == $division->type) { 
    return $next($request); 
} 

abort(403, 'You are not authorized to view this page!'); 
+0

我們如何把'中間件'=> ['division:customer']'? 你能告訴我在routes.php中這個實現的例子嗎? – Orange

+0

@Orange你可以將它應用到你的'Routes'。很可能你想要一個組。答案已更新。 – Ohgodwhy

+0

找不到路線。有人可能會將'division'參數傳遞給原來的'auth'中間件而不創建新的中間件? – Orange