fatkulnurk/laravel-api-request-validation

该包的最新版本(dev-master)没有可用的许可证信息。

其作用是返回json格式的结果,包括导致请求错误的字段、错误信息和旧值。

dev-master 2019-11-18 07:37 UTC

This package is auto-updated.

Last update: 2024-09-18 18:48:54 UTC


README

其作用是返回json格式的结果,包括导致请求错误的字段、错误信息和旧值。

背景

是这样的,最初我确实很困惑,不知道如何为API创建请求验证,后来我在cwhite.me上找到了一篇文章,文章中提到他创建了一个用于抽象Laravel内置表单请求的类。从那时起,我就把它变成了一个包,这样如果需要使用,只需要安装即可。

使用方法

  • 使用composer安装包:composer require fatkulnurk/laravel-api-request-validation
  • 然后运行composer dump-autoload(这不是必须的)。
  • 在您的请求中(默认在app/http/request文件夹),将extends从FormRequest更改为FormRequestApi。

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LoginRequest extends FormRequest
{
    /**
     * 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 [
            'email' => 'required|string|max:191',
            'password' => 'required|string|max:191',
            'remember_me' => 'nullable|boolean'
        ];
    }
}

变成这样

<?php

namespace App\Http\Requests;

use Fatkulnurk\LaravelApiRequestValidation\FormRequestApi;
use Illuminate\Foundation\Http\FormRequest;

class LoginRequest extends FormRequestApi
{
    /**
     * 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 [
            'email' => 'required|string|max:191',
            'password' => 'required|string|max:191',
            'remember_me' => 'nullable|boolean'
        ];
    }
}