LoginSignup
1
1

More than 5 years have passed since last update.

Laravel5.6 Validate機能を実装する

Last updated at Posted at 2018-08-05

保存処理の前にValidateの設定を書きます。

\app\Http\Controllers\ArticleController.php
// Validateをインポート
use Validator;

// 省略

public function add (Request $request)
    {
        // Validation
        // 入力情報の取得
        $inputs = $request->all();

        // ルールを設定
        $rules = [
            'title' => 'required|max:15',
            'body' => 'required|max:256'
        ];

        // エラーメッセージを設定
        $messages = [
            'title.required' => 'タイトルは必須だよ',
            'title.max' => 'タイトルは15文字以内だよ',
            'body.required' => '本文は必須だよ',
            'body.max' => '本文は256文字以内だよ'
        ];

        // 次の引数を渡してValidateする
        $validation = Validator::make($inputs, $rules, $messages);

        // Validateでエラーがでたら
        if ($validation->fails()){
        // 前のページにリダイレクトさせる
            // その際、エラーメッセージをinputデータとともに変数を渡す
            return redirect()->back()->withErrors($validation->errors())->withInput();
        }

        // 保存の処理
        // 省略
    }

画面側の処理
次で、入力されたデータが渡せる


old('title')

次でエラーがあるかどうか分かる。


$errors->has('title')
\resources\views\article\index.blade.php
<div class="row">
    <div class="col-sm-12">
        <form method="POST" action="/article">
            <div class="form-group">
                {{ csrf_field() }}
                <p class="ext-monospace">タイトル</p>
                <input type="text" name="title" class="form-control @if ($errors->has('title')) is-invalid @endif" value="{{old('title')}}">
                @if ($errors->has('title'))
                    <span class="invalid-feedback">{{ $errors->first('title') }}</span>
                @endif
                <br>
                <p class="ext-monospace">本文</p>
                <input type="text" name="body" class=form-control value="{{old('body')}}">
                @if ($errors->has('body'))
                    <span class="invalid-feedback">{{ $errors->first('body') }}</span>
                @endif
                <br>
                <input type="submit" value="投稿" class="btn btn-default">
            </div>
        </form>
        <br><br>
    </div>
</div>

参考にさせていただきました
Laravel5.6: バリデーション(posts)

Laravel 5.6 バリデーション

Laravel(5.1)でCRUD

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