0
0

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】validateメソッドを用いたバリデーション方法

Last updated at Posted at 2020-12-15

validateメソッドとは

Laravelではフォームバリデーション機能が提供されており、validateメソッドはその内の一つです。
実体はIlluminate\Http\Requestクラスのメソッドです。

ちなみに、Illuminateはvender/laravel/framework/src/Illuminateにあります。

validateメソッドによるバリデーションの実装方法

viewの作成

viewを作っていきます。

resources/views/test.blade.php
<form action="submit" method="post">
    <div>
        <label for="title">タイトル:</label>
        <input type="text" id="title" name="title">
    </div>
    <div>
        <label for="body">本文:</label>
        <input type="text" id="body" name="body">
    </div>
    <div>
        <input type="submit" value="送信">
    </div>
    @if ($errors->any())
        <div>
            <ul style="list-style: none;">
                @foreach ($errors->all() as $error)
                    <li style="color: red; font-size: 14px;">{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    {{ csrf_field() }}
</form>

$errorsはLaravelの定義済み変数です。
バリデーションエラーが発生すると、自動的に$errorsにエラーメッセージが格納されます。
@foreachで取り出して使いましょう。

ちなみに、@csrfを書き忘れると、419エラーになってしまうのでちゃんと書きましょう。

参考:【Laravel5】たまに出てくる「the page has expired due to inactivity. please refresh and try again」を表示させない
https://qiita.com/sola-msr/items/8a0ea0abe510245760ac

遷移先ページは以下の感じです。

resouces/views/submit.blade.php
<p>submitted!!</p>

Controllerの作成

TestControllerを作成します。

php artisan make:controller TestController

メソッドを書いていきます。

app/Http/Controller/TestController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index()
    {
        return view('test');
    }

    public function submit(Request $request)
    {
        // バリデーションルールの定義
        $rules = [
            // titleとbodyに入力必須
            'title' => 'required|min:3|max:5',
            'body' => 'required|min:1|max:10',
        ];

        // バリデーション実行
        $request->validate($rules);

        return view('submit');
    }
}

$ruleに連想配列でルールを定義し、$request->validate($rules)でバリデーションを実行しています。

バリデーションルールは、Laravelで定義済みのルールを適用できます。
定義済みルールの一覧は、以下の記事が参考になるのでどうぞ。

参考:Laravelのバリデーションで指定できる内容をざっくりまとめ直しました。
https://qiita.com/fagai/items/9904409d3703ef6f79a2

バリデーションの実行は、$request->validate($rules);の一行で完結です。
OKの場合は処理を続行、NGの場合はリダイレクトの処理を自動でやってくれます。

裏の処理をほとんど意識せずに実装できてしまいますね。

ルーティングの作成

TestControllerのルートを通します。

Route::get('/', 'TestController@index');
Route::post('submit', 'TestController@submit');

表示の確認

以下のようなフォームができました。
image.png

何も入力せずに送信ボタンを押してみます。
image.png
このようにエラーメッセージが表示されます。

バリデーションルールを満たすように、フォームに値を入れて送信ボタンを押すと、問題なく次ページに遷移します。
image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?