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

Laravel5.5LTSの便利なバリデーションの使い方

Last updated at Posted at 2018-05-11

ここに書くのはバリデーションをちょっと実案件向けにアレンジしたものになります。バリデーションルール自体は適当です。

見どころは、前回の入力値の保持と、項目ごとのエラー出力です。
 
フォームリクエストを使用したバリデーションの設定をする。

LoginUserRequest.php
//LoginUserRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LoginUserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'email' => 'required',
        ];
    }

    public function messages() {
        return [
            'email.required' => '「メールアドレス」が未入力です',
        ];
    }
}

 
コントローラーの設定

LoginController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

// 追記する
use App\Http\Requests\LoginUserRequest;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/';

    public function __construct()
    {
    }

    public function authenticate(LoginUserRequest $request)// 追記する
    {
        // 処理
        
        return redirect()->intended('/');
    }
}

viewにて全部のエラーを表示

test.blade.php
@if (count($errors) > 0)
  <div class="alert alert-danger">
      <strong>失敗</strong>入力に誤りがあります<br><br>
      <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
      </ul>
  </div>
@endif

 
項目ごとにエラーを出す場合

test.blade.php

@if ($errors->has('email'))
    <p class="alert">{{ $errors->first('email') }}</p>
@endif
<input type="text" name="email" value="{{ old('email')}}" placeholder="メールアドレス" class="">

$errors->first('email')でemailのエラーメッセージだけを表示する。
old('email')で保持している前回の入力値も表示できる。


エラーサーチという、働くエンジニアのためのメモ帳サービスを運営しています!

自分用の情報をパパッとメモ書きしたり、役立つ情報は整理して他の人にもシェアしたり!
[エラーサーチ] (https://error-search.com/)

[Twitterはこちら] (https://twitter.com/error_search)


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