4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel requestのバリデーションをControllerで受け取りたいとき

Posted at

どうしてもコントローラ側でバリデーションエラーを制御したかったときに実装した内容を備忘録として残します。

バージョン

Laravel Framework 5.5.45
PHP 7.2.25

やったこと

failedValidation を override して、Handlerに飛ばないようにします。
getValidatorを実装して、インスタンスを返せるようにします。

GetIndexRequest.php
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class GetIndexRequest extends FormRequest
{
  /**
   * リクエストに適用するバリデーションルールを取得
   *
   * @return array
   */
  public function rules()
  {
      return [
          'title' => 'required|max:255',
          'body' => 'required',
      ];
  }

    /**
     * 定義済みバリデーションルールのエラーメッセージ取得
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required' => 'A title is required',
            'body.required'  => 'A message is required',
        ];
    }

    /**
     * @param Validator $validator
     */
    protected function failedValidation(Validator $validator)
    {
    }

    /**
     * @return  Validator  $validator
     */
    public function getValidator()
    {
        return $this->getValidatorInstance();
    }
}

Controller側で受け取ってみます。

HogeController.php
public function find(GetIndexRequest $request)
{
    $validator = $request->getValidator();
    if ($validator->fails()) {
       // エラーが表示される
        echo $validator->getMessageBag()->first();
    }
}
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?