0
1

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 3 years have passed since last update.

【Laravel】FormRequestでバリデーションを実装しよう

Last updated at Posted at 2021-09-20

はじめに#

バリデーションとは、入力内容が要件を満たしているかどうか確認することです。
LaravelではFormRequestを使って簡単にバリデーションが実装できます。

FormRequestのメリット#

 FormRequestを使うことで、バリデーションのルールやエラー時の処理をコントローラーから分離することが出来ます。また、バリデーションの使い回しやカスタマイズもしやすくなります。

どうやって実装するのか#

 まずはRequestクラスを継承したPostFormRequestを作ります。
このようにコマンド入力します。

php artisan make:request PostFormRequest

これでPostFormRequestクラスを作ることが出来ます。
次に、生成されたPostFormRequestクラスに次のように記述します。

PostFormRequest.php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostFormRequest 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 [
            'name' => 'required|max:20',
            'post' => 'required|max:140'
        ];
    }

}

public function authorize()の中身をtrueにするのを忘れないようにしましょう。
バリデーションのルールはpublic function rules()の中に書いていきます。
今回の例だと、name(フォームタグのname属性の値)には必須入力、最大文字数20文字というルールが与えられています。入力内容がこれに逸脱すると、バリデーションに引っかかって自動で前のページにリダイレクトするようになります。
 当然、エラーメッセージを表示することもできます。

post.blade.php
/** エラーを全てまとめて表示 */
@if(count($errors) > 0)
      <div class="alert alert-danger">
             <ul>
                 @foreach($errors->all() as $error)
                       <li>{{ $error }}</li>
                 @endforeach
             </ul>
       </div>
@endif

/** 特定のエラーを表示 */
@if($errors->has('name'))
  <div class="error alert alert-danger">
    <p>{{ $errors->first('name') }}</p>
  </div>
@endif

まとめ#

・Laravelでバリデーションを実装する際はFormRequestを使う。
・FormRequestクラスにバリデーションルールを記入する。
・viewでエラーを表示する。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?