0
2

More than 3 years have passed since last update.

Laravelのバリデーションにフォームリクエストバリデーションを使ってみた

Last updated at Posted at 2021-01-31

はじめに

自分の記録としてなのでわかりにくい箇所があったら申し訳ありません。
不明点があれば、ページの最後に参考にさせて頂いたリンクを張っているのでそちらを見てみてください

フォームリクエストバリデーションとは

  • ファイル置き場所はapp/Http/Requests/
  • バリデーションエラー時には、入力値とエラー情報を付与して前のページにリダイレクトしてくれる
  • artisanコマンドで生成できる

手順

さっそくフォームリクエストを使用していきましょう
コマンドは
php artisan make:request StoreBuy

実行すると app/Http/Requests/StoreBuy.phpができます。

StoreBuy.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreBuy 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 [
            'name'=>'required|max:20',
            'postalcode'=>'required',
            'region'=>'required',
            'addressline1'=>'required',
            'phonenumber'=>'required'
        ];
    }
}

今回自分はこのように記述しました。
public function rules()から自分がバリデーションをかけたいフィールドにルールを記述。
ルールは目的にそったものでカスタマイズしましょう。
それと、return trueの箇所ですが、初期状態はfalseになっているので、trueに変更してください。
falseのままだとうまく動きません。
使用できるバリデーションルールはこちらのページを参照してみてください
https://readouble.com/laravel/6.x/ja/validation.html

コントローラーを編集

BuyController.php
use App\Http\Requests\StoreBuy; //コントローラーに追記
   public function store(StoreBuy $request) //引数を修正
    {
        if($request->has('post')){
            Mail::to(Auth::user()->email)->send(new Buy());
            CartItem::where('user_id',Auth::id())->delete();
            return view('buy/complete');
        }
        $request->flash();
        return $this->index();
    }

コントローラーの引数をフォームリクエストバリデーションに変更

viewにエラーメッセージを表示

@if($errors->any())
<div class="alert alert-danger">
    <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

ここはviewに表示するだけなのですが参考までに
if文で何がエラーが入っていたら表示という形になります
※classはBootstrapの書き方です。

今回参考したページ

最後になりましたが、今回参考にさせて頂いたページです
Laravel学習帳
https://laraweb.net/knowledge/2156/

Qiita
https://qiita.com/sakuraya/items/abca057a424fa9b5a187

0
2
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
2