ミドルウェアの適用
コントローラー単位でアクション→ビューにアクセス制限をかける場合。コントローラーのコンストラクターでアクセス制限のミドルウェアを適用する。
$this->middleware('auth')
特定のアクションのみに適用したり、逆に適用除外にするには、only()/except()を使う。
たとえばマーケットサイトのCartControllerへのルーティングで、ログインユーザーのみ処理させるには以下の様にコントローラーを書く。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class CartController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { .... } .... } |
こうすると、ログイン状態でアクセスするとindexなどのアクションが実行されてビューに遷移するが、ログイン状態でない場合はログインページに遷移する。
middleware(‘auth’)
コンストラクターの$this->midlleware('auth')は、コントローラーの全アクションに対して名前'auth'のミドルウェアを適用する。
'auth'はKernel.phpでルートミドルウェアAuthenticateに結び付けられている。
|
1 2 3 4 5 6 |
protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, .... ]; |
Authenticateミドルウェア
Authenticateミドルウェアは、Laravelのプロジェクト作成時にapp/Middlewareディレクトリーに生成されている。
- このミドルウェアの
handle()メソッドはIlluminate\Auth\Middleware\Authenticateで定義されている $request->expectsJson()でログイン状態にあるかどうかを判定しているようだが、その流れはよくわかっていない
この'login'へのルーティングを変更すると、未ログインの場合の遷移先を変更できる。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php namespace App\Http\Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware; class Authenticate extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ protected function redirectTo($request) { if (! $request->expectsJson()) { return route('login'); } } } |