Saturday, February 19, 2022

[FIXED] how to get an error key in laravel error message array

Issue

I am trying to retrieve a key from an array using Laravel error dump ($errors).

The array looks like this

ViewErrorBag {#169 ▼
  #bags: array:1 [▼
    "default" => MessageBag {#170 ▼
      #messages: array:2 [▼
        "name" => array:1 [▼
          0 => "The name field is required."
        ]
        "role_id" => array:1 [▼
          0 => "The role id field is required."
        ]
      ]
      #format: ":message"
    }
  ]
}

Using @foreach loop to get the error message works fine.

@foreach($errors->all() as $error)
     <li>{{$error}}</li>
@endforeach

But I want to get that name and role_id. Is there anyway to achieve that? Thus far i have tried the below and some other methods with no luck.

@foreach ($errors->all() as $key => $value)
       Key: {{ $key }}
       Value: {{ $value }}
@endforeach

Solution

It's because, the $errors->all() returns an array of all the errors for all fields in a single array (numerically indexed).

If you want to loop and want to get each key => value pairs then you may try something like this:

@foreach($errors->getMessages() as $key => $message)
    {{$key}} = {{$message}}
@endforeach

But , you may explicitly get an item from the errors, for example:

{{ $errors->first('name') }} // The name field is required.

Maybe it's wise to check before you ask for any error for a field using something like this:

@if($errors->has('name'))
    {{ $errors->first('name') }}
@endif

This'll help you to show each error at the top/bottom of the field that the error belongs to.



Answered By - The Alpha

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.