使用 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不起作用

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
最佳答案

经测试,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年前 评论

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