使用 Dingo\API\Http\FormRequest,在 Request 设置 attributes 不起作用?

<?php

namespace App\Http\Requests\Api;

use Dingo\Api\Http\FormRequest;

class UserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|between:3,25|regex:/^[A-Za-z0-9\-\_]+$/|unique:users,name',
            'password' => 'required|string|min:6',
            'verification_key' => 'required|string',
            'verification_code' => 'required|string',
        ];
    }

    public function attributes()
    {
        return [
            'verification_key' => '短信验证码 key',
            'verification_code' => '短信验证码',
        ];
    }
}

使用Dingo\Api\Http\FormRequest,在Request设置attributes不起作用

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

经测试,Dingo 包的 FormRequest 中,validate 方法不支持自定义 attribute 的功能。

问题代码:

// 位置 vendor/dingo/api/src/Http/FormRequest.php 
// 没有传入自定义 attributes 字段代码
$validator = app('validator')->make($this->all(), $this->rules(), $this->messages());

建议:

可以新建一个 FormReqeust 基类,修改 validate 方法为如下样式

public function validate()
{
    if ($this->authorize() === false) {
        throw new AccessDeniedHttpException();
    }

    //  传入自定义 attributes 
    $validator = app('validator')->make($this->all(), $this->rules(), $this->messages())
        ->setAttributeNames($this->attributes());

    if ($validator->fails()) {
        throw new ValidationHttpException($validator->errors());
    }
}

之后所有的验证类都继承此修改后的新基类。

以上,应该可以满足楼主需求。

4年前 评论
讨论数量: 2

建议你用 messages() 来定义错误信息好了

4年前 评论

经测试,Dingo 包的 FormRequest 中,validate 方法不支持自定义 attribute 的功能。

问题代码:

// 位置 vendor/dingo/api/src/Http/FormRequest.php 
// 没有传入自定义 attributes 字段代码
$validator = app('validator')->make($this->all(), $this->rules(), $this->messages());

建议:

可以新建一个 FormReqeust 基类,修改 validate 方法为如下样式

public function validate()
{
    if ($this->authorize() === false) {
        throw new AccessDeniedHttpException();
    }

    //  传入自定义 attributes 
    $validator = app('validator')->make($this->all(), $this->rules(), $this->messages())
        ->setAttributeNames($this->attributes());

    if ($validator->fails()) {
        throw new ValidationHttpException($validator->errors());
    }
}

之后所有的验证类都继承此修改后的新基类。

以上,应该可以满足楼主需求。

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!