Laravel自定义验证消息作为数组导致错误

时间:2017-08-04 15:47:07

标签: php validation laravel-5.4

在一个包中,我试图在与Laravel的默认文件分开的文件中包含自定义验证错误消息。我复制了文件,更改了值(没有触摸键),在服务提供商中正确加载,一切正常。基本验证(例如requirednumericemail等在我的文件中显示了该文本。现在,我尝试使用size规则,但由于错误消息在数组中,因此在使用$errors->get( 'content.reasons' )时会出现此异常:

Array to string conversion in MessageBag.php (line 246)

这里是代码的重要部分

控制器

$validator = Validator::make( $request->all(), $rules, trans( 'admin::validation' ) );
if ( $validator->fails() ){
    return redirect()
        ->back()
        ->withInput()
        ->withErrors( $validator );
}

$request->all()

[
    // ...
    "content" => [
        "reasons" => [
            [...],
            [...]
        ]
    ],
    // ...
]

$rules

[
    // ...
    "content.reasons" => "required|size:3"
    // ...
]

trans( 'admin::validation' )

// Exact structure of Laravel validation.php
[
    // ...
    'size'                 => [
        'numeric' => 'The field must be :size.',
        'file'    => 'The field must be :size kilobytes.',
        'string'  => 'The field must be :size characters.',
        'array'   => 'The field must contain :size items.',
    ],
    // ...
]

重定向后

$errors = session()->get('errors') ?: new ViewErrorBag;
$field[ 'errors' ] = $errors->get( $dot_name ); // Exception thrown when $dot_name
                                                // equals `content.reasons`.

$errors

Illuminate\Support\ViewErrorBag {
    #bags: array:1 [
        "default" => Illuminate\Support\MessageBag {
            #messages: array:4 [
                "content.why_title" => array:1 [
                    0 => "The field is required."
                ]
                "content.reasons" => array:1 [
                    0 => array:4 [
                        "numeric" => "The field must be 3."
                        "file" => "The field must be 3 kilobytes."
                        "string" => "The field must be 3 characters."
                        "array" => "The field must contain 3 items."
                    ]
                ]
                "content.reasons.0.icon" => array:1 [
                    0 => "The field is required."
                ]
                "content.reasons.0.text" => array:1 [
                    0 => "The field is required."
                ]
            ]
            #format: ":message"
        }
    ]
}

我尝试传递content.reasons.array,但它返回一个空数组。

我也尝试不传递任何消息(使用Laravel的默认设置)并且它有效,但我确实需要自定义消息...

TL; DR:我们如何传递与Laravel具有相同架构的自定义消息?

1 个答案:

答案 0 :(得分:1)

我不知道您要做什么,但您可以为每个验证字段/规则传递自定义消息,例如,在您的控制器中:

  kernel.Bind<IInitialUploadFolderCleaner>().To<InitialUploadFolderCleaner>().WithConstructorArgument("siteRootPath", HostingEnvironment.ApplicationPhysicalPath);


        kernel.Bind(x =>
        {
            x.FromAssembliesMatching("MyPrefix.*")
                .SelectAllClasses()
                .BindDefaultInterface();
        });