Laravel

Laravel Requestによるバリデーション

優 Laravel

Laravel

Laravelのリクエストを利用すると、コントローラに処理が渡る前にバリデーションなどの処理が出来ます。リクエストを利用することでコントローラの肥大化を防ぐことが出来て処理がわかりやすくなります。

 

 

ひな形の作成 バリデーションを記述しよう

artisanでPersonRequestを作成します。

php artisan make:request PersonRequest

 

/project/app/Http/Requests/PersonRequest.phpが作成される

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PersonRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
            return true; //基本これで
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'     => 'required', // 必須
            'age'      => 'required|integer' // 必須, 整数型
            'comment'  => 'required|string', //必須, 文字列
            'password' => 'required', // 必須
            'image'    => 'file|image|max:10000', // 画像チェック, 10MB以内
            'email'    => 'email', //メールアドレスチェック

        ];
    }

    public function messages()
    {
        return [
            'name.required'     => '名前は必ず入力して下さい。',
            'age'               => '年齢は必ず入力して下さい、また半角数字でお願いします。',
            'comment.required'  => '本文は必ず入力して下さい。',
            'password.required' => '編集用パスワードは必ず入力して下さい。',
        'image'             => '画像を10MB以内でアップロードして下さい(jpg、png、bmp、gif対応)',
            'email'             => 'メールアドレスが正しいか確認して入力して下さい',
        ];
    }

}

rulesでリクエストに対するルールを記述し、message()でエラーメッセージを上書き(オーバライド)しましょう。書かないと英語のエラーメッセージがでるYO!

 

リファレンス

他にも便利なバリデーションルールがLaravel側で用意されているので、リファレンスをチェックしましょう。
https://readouble.com/laravel/5.5/ja/validation.html

基本的にLaravelのバリデーションルールで記述して、対応出来ないものは自分でバリデーションを書いていけば効率的ですね。

 

コントローラにリクエストを指定する

user_create()にPersonRequestを指定します。

/project/app/Http/Controllers/PersonController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\PersonRequest;
use App\Models\Person;

class PersonController extends Controller
{

    public function user_create(PersonRequest $request){
        $people = new Person();
        $people->create($request);
        return redirect('/');
    }
}

user_create()メソッドにPersonRequestでリクエストインスタンスを指定することで、PersonRequestクラスで記述したバリデーションを利用できるし、使いまわしたり、使わなかったりすることが簡単に出来ます。

 

表示 bladeでエラーメッセージを出力しよう

 

/project/resources/views/users/add.blade.php

@extends('layouts.layout')
@section('title', '新規投稿ページ')
@section('content')
 <div class="page-header" style="margin-top:-30px;padding-bottom:0px;">
  <h1><small>わくわく掲示板</small></h1>
 </div>

  <h2><small>書き込み</small></h2>
  @if(count($errors) > 0)
  <p>入力に問題があります。再入力して下さい。</p>
  @endif
  <table class="table table-striped table-hover">
  <thead>
  </thead>
  <tbody>
  {{Form::open(['action' => 'PersonController@user_create', 'files' => true])}}
      {{ csrf_field() }}
      @if($errors->has('name'))
      <tr><th>エラー!</th><td>{{ $errors->first('name') }}</td></tr>
      @endif
      <tr><th>名前*</th><td><input type="text" name="name"></td></tr>

(略)

名前が未入力でフォームを送信すると「名前は必ず入力して下さい。」というエラーが出ます。

 

 

お疲れ様です。

Laravel
最新情報をチェックしよう!
>システム構築・保守に特化した会社です。

システム構築・保守に特化した会社です。

システムの構築・保守運用「システムガーディアン」 社内システム担当が欲しいが、専属で雇うほどの仕事量はない。 必要な時に必要なだけ頼りたいというお悩みを持つ企業様へ専門知識を持って対応を行っております。 サーバから各種システムまで自社・他社で構築されたシステムに対してサポートを行っております。

CTR IMG