概要
- リクエストクラスを
$ php artisan make:request
で作成した時にできるファイルに最初から記載されているauthorize()
関数は認証の必要がなければ関数そのものを記載しなくていいという記事をどっかで見た気がして本当か見てみる。
詳細
-
下記コマンドを実行して作成したリクエストクラスのファイルを用いて継承元などをたどってみる。
$ php artisan make:request WorkUpdateRequest
たどってみた
-
まずは
$ php artisan make
コマンドで作成したリクエストクラスのファイルを見てみる。(当該ファイルは実際に使用中なので色々記載されている)WorkUpdateRequest.php<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class WorkUpdateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'start_date_time' => 'required|date', 'end_date_time' => 'required|date', // 本クラス内で作成した値のバリデーション // date-time-consistencyはstart_date_time < end_date_timeの場合true 'start_and_end' => 'required|date-time-consistency', ]; } /** * バリデーションチェック前の処理 * * @return void */ public function prepareForValidation() : void { $this->merge([ 'start_and_end' => [ 'start_date_time' => $this->get('start_date_time'), 'end_date_time' => $this->get('end_date_time'), ], ]); } }
-
extends FormRequest
となっている通り、FormRequestクラスが継承されているので継承元の関係ありそうな関数を見てみる。FormRequest.php/** * Determine if the request passes the authorization check. * * @return bool */ protected function passesAuthorization() { if (method_exists($this, 'authorize')) { return $this->container->call([$this, 'authorize']); } return true; }
-
↑
passesAuthorization()
関数はauthorize()
関数が合った場合、当該の関数をコールする。無かった場合trueを返している。 -
passesAuthorization()
関数はvendor/laravel/framework/src/Illuminate/Validation/ValidatesWhenResolvedTrait.php
で使用されており、当該のクラスをFormRequestクラスでuse宣言している。/** * Validate the class instance. * * @return void */ public function validateResolved() { $this->prepareForValidation(); if (! $this->passesAuthorization()) { $this->failedAuthorization(); } $instance = $this->getValidatorInstance(); if ($instance->fails()) { $this->failedValidation($instance); } $this->passedValidation(); }
まとめ
- リクエストクラスの
authorize()
が定義されていなかった場合、継承元クラスにてpassesAuthorization()
を返すから大丈夫そう