【问题标题】:Validation in Laravel. How to transfer the rule and message to the controller?Laravel 中的验证。如何将规则和消息传递给控制器​​?
【发布时间】:2019-02-22 22:51:26
【问题描述】:

我在显示自定义错误消息时遇到问题。 我收到了一个包含以下代码的培训项目:

class StoreProject extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'name' => 'required|unique:projects,name|max:255',
            'website' => 'url',
        ];
    }

    public function messages()
    {
           return [
                'name' => 'Це імʼя вже використовується',
                'website' => 'Будь-ласка введіть адресу вашого сайту вірно http://...'
            ];
    }
}

我自己添加了函数 message()。

这是控制器代码:

public function store(StoreProject $request)
{

    $project = new Project($request->except('project_image'));

    $project->owner_id = Auth::user()->id;
    $project->status_id = StatusProject::UNCONFIRMED;

    //send email to moderator and accountant for the moderation
    if( $project->save() ) {
        $this->dispatch(new ConfirmNewProject($project));
    }

    // load image from cropie serves
    if ($request->has('project_image')) {
        $file = self::croppie($request->input("project_image"));
        $project->uploadImage($file, 1);
    }

    return redirect()->route('projects.show', [$project->id]);
}

我尝试了各种方法:withErrors([]) 和这个方法:

'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
            'name' => 'Це імʼя вже використовується',
            'website' => 'Будь-ласка введіть адресу вашого сайту вірно http://...'
        ],
    ]

但在检查时,我得到的是键值,而不是错误消息的文本

错误: 验证.唯一 验证.url

如何将规则和消息传递给控制器​​?

【问题讨论】:

标签: laravel validation rules


【解决方案1】:

尝试像这样修改messages()函数:

public function messages()
{
       return [
            'name.required' => 'Name required message',
            'name.unique' => 'Name unique message',
            'name.max' => 'Name max message',
            'website.url' => 'Будь-ласка введіть адресу вашого сайту вірно http://...'
        ];
}

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多