LoginSignup
0
1

More than 3 years have passed since last update.

Laravel バリデーションを設定する ~フォームリクエスト編~

Last updated at Posted at 2021-02-10

目的

  • リクエストにバリデーションを記載する方法をまとめる

実施環境

  • ハードウェア環境
項目 情報
OS macOS Catalina(10.15.3)
ハードウェア MacBook Pro (16-inch ,2019)
プロセッサ 2.6 GHz 6コアIntel Core i7
メモリ 16 GB 2667 MHz DDR4
グラフィックス AMD Radeon Pro 5300M 4 GB Intel UHD Graphics 630 1536 MB
  • ソフトウェア環境
項目 情報 備考
PHP バージョン 7.4.3 Homwbrewを用いて導入
Laravel バージョン 7.0.8 commposerを用いて導入
MySQLバージョン 8.0.19 for osx10.13 on x86_64 Homwbrewを用いて導入

前提情報

  • ターミナルコマンドは基本的に$ laravel newコマンドで作成されたアプリ名ディレクトリで実行するものとする。
  • ブラウザ上でコンテンツを新規作成する際にコンテンツタイトルとコンテンツ詳細に入力がない場合にバリデーションで弾く処理を追加する。

概要

  1. フォームリクエストクラスの作成
  2. コントローラの修正
  3. ビューファイルの修正
  4. 確認

詳細

  1. フォームリクエストクラスの作成

    1. 下記コマンドを実行してフォームリクエストクラファイルの作成を行う。

      $ php artisan make:request StoreContentPost
      
    2. 下記コマンドを実行して先に作成したフォームリクエストクラスファイルを開く。

      $ vi app/Http/Requests/StoreContentPost.php
      
    3. 開いたフォームリクエストクラスファイルを下記の様に修正する。

      アプリ名ディレクトリ/app/Http/Requests/StoreContentPost.php
      <?php
      
      namespace App\Http\Requests;
      
      use Illuminate\Foundation\Http\FormRequest;
      
      class StoreContentPost 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 [
                  //バリデーションルールを記載する
                  //'チェックするデータ名' => 'ルール1|ルール2'の様にルールを定義する
                  'title' => 'required',
                  'detail' => 'required',
              ];
          }
      }
      
  2. コントローラファイルの修正

    1. 下記コマンドを実行してコントローラファイルを作成する。

      $ vi app/Http/Controllers/ContentController.php
      
    2. 開いたコントローラファイルを下記の様に修正する。

      アプリ名ディレクトリ/app/Http/Controllers/ContentController.php
      <?php
      
      namespace App\Http\Controllers;
      
      //use Illuminate\Http\Request;
      //下記を追記する
      use App\Http\Requests\StoreContentPost;
      
      use App\Content;
      
      class ContentController extends Controller
      {
          public function index()
          {
              $contents = Content::all();
              return view('contents.index', ['contents' => $contents]);
          }
      
          public function create()
          {
              return view('contents.create');
          }
      
          //下記を修正する
          public function save(StoreContentPost $request)
          {
              $new_content = new Content();
              $new_content->title = $request['title'];
              $new_content->detail = $request['detail'];
              $new_content->save();
      
              return redirect(route('content.index'));
          }
      
          public function detail($content_id)
          {
              $content = Content::find($content_id);
              return view('contents.detail', ['content' => $content]);
          }
      
          public function edit($content_id)
          {
      
              $content = Content::find($content_id);
              return view('contents.edit', ['content' => $content]);
          }
      
          //下記を修正する
          public function update($content_id, StoreContentPost $request)
          {
              $content = Content::find($content_id);
              $content->title = $request['title'];
              $content->detail = $request['detail'];
              $content->save();
              return redirect(route('content.index'));
          }
      
          public function destroy($content_id)
          {
              $content = Content::find($content_id);
              $content->delete();
              return redirect(route('content.index'));
          }
      
      }
      
  3. ビューファイルの修正

    1. 下記コマンドを実行して新規登録する時に表示しているビューファイルを開く。

      $ vi resources/views/contents/create.blade.php
      
    2. 開いたビューファイルを下記の様に修正してエラー文を表示できる様にする。

      アプリ名ディレクトリ/resources/views/contents/create.blade.php
      <h1>create</h1>
      
      <form action="{{route('content.save')}}" method="post">
          @csrf
          <h3>タイトル</h3>
          {{-- 下記を追記する --}}
          @if ($errors->has('title'))
              @foreach ($errors->get('title') as $title_errors)
                  <p>{{$title_errors}}</p>
                  <br>
              @endforeach
          @endif
          {{-- 上記までを追記する --}}
          <input type="text" name="title">
          <br>
          <h3>内容</h3>
          {{-- 下記を追記する --}}
          @if ($errors->has('detail'))
              @foreach ($errors->get('detail') as $detail_errors)
                  <p>{{$detail_errors}}</p>
                  <br>
              @endforeach
          @endif
          {{-- 上記までを追記する --}}
          <textarea name="detail" cols="30" rows="10"></textarea>
          <br>
          <input type="submit" value="保存">
          <input type="button" onclick="location.href='{{ route('content.index') }}'" value="一覧に戻る">
      </form>
      
  4. 確認

    1. 各種情報入力画面でバリデーションルールと異なる情報を入力した時にエラーが表示されれば作業完了である。
0
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
0
1