LoginSignup
0
0

More than 3 years have passed since last update.

エラーバンドリングの表示

Last updated at Posted at 2020-10-18

【概要】

1.結論

2.どのようにコーディングするか

3.開発環境

補足

1.結論

@if (count($errors) > 0) と、@foreachを使用する!

2.どのようにコーディングするか

@if@foreach の使い方は自分のこちらの記事にて説明しているので、よかったらご覧ください!
blade構文

resorces/views/hoge/index.blade.php
<p>{{$msg}}</p>
 @if (count($errors) > 0)
  <div>
   <ul>
    @foreach ($errors->all() as $error)
     <li>{{$error}}</li>
    @endforeach
   </ul>
  </div>
 @endif

エラーメッセージあれば、そのエラーの全てをそれぞれ取り出すようにしています。そしてそれを変数を用いて表示しています。

ただ、バリデーションがかかっていることが前提なので下記のようにコーディングしています。

app/Http/Controllers/HogeController.php

class HogeController extends Controller
{
    public function index(Request $request)
    {
      return view('hoge.index', ['msg'=>'入力してください:']);
    }

    public function post(Request $request)
    {
      $validate_rule = [
        'name' => 'required' ,
        'mail' => 'email' ,
        'age' => 'numeric|between:0,150' ,
        ];
        $this->validate($request , $validate_rule);
        return view('hoge.index' , ['msg'=>'正しく入力してください']);
    }
}


3.開発環境

Mac catalina 10.15.4
Vscode
PHP 7.4.10
Laravel 8.9.0
Apache 2.4.41

補足

エラーバンドリングを表示させるということは2.のあとにform要素を付け加えると思います。その際に@csrfの記載を忘れないでください。セキュリティ対策になります。

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