7
8

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.

Laravelで画面とAPIで共通のFormRequestを使う方法

Last updated at Posted at 2018-09-03

前提

Laravel 5.x

書くこと

画面でPOSTするときとJSONでポストされたとき、同じFormRequestを使いたかった
→ 共通のFormRequestで画面もJSON応答でも使えるように考えてみた
思いつきなので、「こっちのほうがよいよ!」とかあればコメントお願いします。

書いたコード

Githubはこちら

App/Http/Requests/TodoFormRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

/**
 * HTMLのFORM POST時に使うFormRequest
 */
class TodoFormRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

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

    public function attributes()
    {
        return [
            'task_name' => 'タスク名',
            'remarks' => '備考',
        ];
    }
}
App/Http/Requests/Common/ApiFormRequestTrait.php
<?php

namespace App\Http\Requests\Common;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * FormRequestのバリデート結果をJSONに変換して返却するトレイト
 */
trait ApiFormRequestTrait
{
    protected function failedValidation( Validator $validator )
    {
        $response['data']    = [];
        $response['status']  = 'NG';
        $response['summary'] = 'Failed validation.';
        $response['errors']  = $validator->errors()->toArray();
        $response['errorMessages']  = $validator->errors()->all();
        

        throw new HttpResponseException(
            response()->json( $response, 422 )
        );
    }
}
App/Http/Requests/Api/TodoApiFormRequest.php
namespace App\Http\Requests\Api;

use App\Http\Requests\Common\ApiFormRequestTrait;
use App\Http\Requests\TodoFormRequest;

/**
 * AjaxなどApi用Controllerで使われるFormRequest
 */
class TodoApiFormRequest extends TodoFormRequest
{
    use ApiFormRequestTrait;
}

どんなときに使うの?

HTMLのFormでPOSTする・AjaxでPOSTするの両ケースが存在する場合
(本当にある……? は横に置いておきます)

参考にさせていただいたページ

https://qiita.com/junsan50/items/ec7f810decd3b82d3d76
(ApiFormRequestTrait.php の内容はそのまま頂いています)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?