LoginSignup
0
1

More than 3 years have passed since last update.

LaravelでFormRequestを使ってバリデーションする方法

Posted at

Controllerが肥大化(MVCの宿命)してしまうのを少しでも解決するために、バリデーションはFormRequestを使って処理するのが良さそうだったので、自分用のメモとして使い方をまとめてみた。

FormRequestとは

バリデーションルールを外部クラス(FormRequestクラス)にまとめることができ、任意の処理で呼び出すことができる
FormRequestを下記のようにDIしてあげると、バリデーションが通った時だけコントローラー内の処理が走るようになります
このようにバリデーションを外部クラスで処理することでControllerでは自分の処理に専念することができる

public function store(StoreRequest $request)
{
  // バリデーションが通ったときにここの処理が走る
}

使ってみる

artisanコマンドで作成できる

php artisan make:request StoreRequest
StoreRequest.php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true; // デフォルトはfalse(アクセス権限を付けない場合はtrueにする)
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // ここにバリデーションルールを書いていく
        ];
    }
}

バリデーションルール

    public function rules()
    {
        return [
           'title' => 'required|unique:posts|max:255',
           'body' => 'required',
        ];
    }

こんな感じで書く

バリデーションエラー時のレスポンスをjsonに変更

デフォルトではレスポンスがHTMLのためAPI開発などでも扱いやすいようjsonに変更する
バリデーションエラー時に実行されるfailedValidationメソッドをオーバーライドする

    protected function failedValidation(Validator $validator)
    {
        $res = response()->json([
            'status' => 400,
            'errors' => $validator->errors(),
        ],400);
        throw new HttpResponseException($res);
    }

他にも色々な機能がある

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1