【问题标题】:how to access validation error property name in Laravel?如何在 Laravel 中访问验证错误属性名称?
【发布时间】:2020-02-19 08:11:30
【问题描述】:

我来自 Laravel,我尝试验证它并查看每个输入的错误,我已经循环通过 $error->all() 但我需要显示其下每个输入的错误,我使用此代码 $errors->has('password') 来显示输入有错误,但我也需要显示消息。 我得到print_r($errors) 并返回:

Illuminate\Support\ViewErrorBag Object
(
    [bags:protected] => Array
        (
            [default] => Illuminate\Support\MessageBag Object
                (
                    [messages:protected] => Array
                        (
                            [firstName] => Array
                                (
                                    [0] => The first name field is required.
                                )

                            [lastName] => Array
                                (
                                    [0] => The last name field is required.
                                )

                            [email] => Array
                                (
                                    [0] => The email must be a valid email address.
                                    [1] => The email field is required.
                                )

                            [password] => Array
                                (
                                    [0] => The password field is required.
                                )

                            [password_confirmation] => Array
                                (
                                    [0] => The password confirmation field is required.
                                )

                        )

                    [format:protected] => :message
                )

        )

)

我的问题是我无法访问这些消息?

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.8 php-7.2


    【解决方案1】:

    根据 Laravel 文档,您可以使用 @error 指令来实现相同的效果

    $errors 变量通过 Illuminate\View\Middleware\ShareErrorsFromSession middleware,即 由网络middleware 组提供。应用此中间件时 $errors 变量将始终在您的视图中可用,允许 您可以方便地假设 $errors 变量总是被定义并且 可以放心使用。

    例如

    <label for="title">Post Title</label>
    
    <input id="title" type="text" class="@error('title') is-invalid @enderror">
    
    @error('title')
        <div class="alert alert-danger">{{ $message }}</div>
    @enderror
    

    Laravel -> Validation -> Displaying The Validation Errors

    【讨论】:

    • 欢迎。继续学习..并且不要忘记接受并支持答案:)
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2015-11-09
    • 1970-01-01
    • 2020-05-27
    • 2020-06-14
    • 2021-08-13
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多