2016-07-08 4 views
0

私が試みてきたのは、ユーザーのタイプに基づいてmiddlewareに異なるタスクをさせることです。Laravel 5の認証:ユーザーの種類に応じて、訪問者を別のページにリダイレクトしますか?

ここにルートグループがあります。

Route::group(array('prefix' => 'api', 'middleware' => 'admin'), function() { 
    Route::resource('animal', 'AnimalController'); 
    //Other resources 
}); 

マイUserモデルは、以下の方法によってアクセスすることができる2種類を有しています。

$this->user()->user_type_id; 

Following this advice,私はこの仕事をしようとしていた、とApp\Http\Middleware\Authenticatehandle機能は今、この権利のように見えます。

public function handle($request, Closure $next) 
{ 
    if ($this->auth->guest()) { 
     if ((Auth::user()->user_type_id == 2) { 
      //If the user is of type 2, this will be triggered 
      if ($request->ajax()) { 
       return response('You are type 2.', 401); 
      } 
      //Maybe there are other libes here 
     } else if ($request->ajax()) { 
      return response('Unauthorized.', 401); 
     } else { 
      return redirect()->guest('auth/login'); 
     } 
    } 
    return $next($request); 
} 

私は、ユーザーがapi/animalで始まるURLを訪れたときに、これはresponse('You are type 2.', 401)を取得するにはタイプ2のユーザーを導くだろうと思ったが、私は応答メッセージUnauthorized.を見ました。

このような方法で認証ミドルウェアを使用することはできますか? アドバイスをいただければ幸いです。

+0

デフォルトでは、 'App \ Http \ Middleware \ Authenticate :: class'は' admin'ではなく 'auth'としてマップされています。ルート定義のミドルウェア名を変更すると何かが変更されるかどうかを確認してください。 – korun

+0

korunありがとう、はい、私はedittedとして実際にそれを変更しました。 – Hiroki

答えて

0
if ($this->auth->guest()) { 
    if ($request->ajax()) { 
     return response('Unauthorized.', 401); 
    } else { 
     return redirect()->guest('auth/login'); 
    } 
} else if ($this->user()->user_type_id == 2) { 
    //If the user is of type 2, this will be triggered 
    return response('You are type 2.', 401); 
} 

これを試してください。

関連する問題