Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

Laravel5.1入門その11 カスタムバリデーション

Controllerのアクションの最初にリクエストパラメータをずらずら書くとノイズになりがちだ。

<?php
namespace App\Http\Controllers;

//...

class BookCharacterController extends Controller
{
  public function store(Request $request)
  {
    $this->validate($request, [
      'title' => 'required|unique:posts|max:255',
      'body' => 'required',
      // たくさんの
      // パラメータ
      //
      //
      //
      //
    ];

    // ここからやっとメインの処理
  }
}

手っ取り早く分離するにはリクエストバリデーションを作ってしまうのが良さそう。

$ php artisan make:request StoreBookRequest

app/Http/Requests/StoreBookRequest.php

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class StoreBookRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

認証は、だいたいはMiddlewareでやるものだと思うので、authorize()はtrueを返すようにして、
あとはrulesの中に、最初のvalidationの指定を移動させれば、ok。

<?php
//...
public function authorize()
{
  return true;
}

public function rules()
{
  return [
      'title' => 'required|unique:posts|max:255',
      'body' => 'required',
      // たくさんの
      // パラメータ
      //
      //
      //
      //
  ];
}

あとはControllerで引数にタイプヒンティングを利用したDIで、検証済みのRequestオブジェクトをもらう。

<?php
//...
use App\Http\Requests\StoreBookRequest;

class BookCharacterController extends Controller
{
  public function store(StoreBookRequest $request)
  {
     // メインの処理
  }
}

すっきり。