Skip to content
Advertisement

how to access validation error property name in Laravel?

I have from in Laravel and I try to get validate it and see errors for each input, I already loop through $error->all() but I need to show the errors of each input under it and I use this code $errors->has('password') to show input have an error but I need to show message too. I get print_r($errors) and It return this:

IlluminateSupportViewErrorBag Object
(
    [bags:protected] => Array
        (
            [default] => IlluminateSupportMessageBag 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
                )

        )

)

My problem is I can’t how can access the messages?

Advertisement

Answer

AS per Laravel Documentation you can use @error directive to achieve the same

The $errors variable is bound to the view by the IlluminateViewMiddlewareShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

for e.g

<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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement