Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get an error key in laravel error message array

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
like image 370
Mohamed Athif Avatar asked Sep 17 '16 22:09

Mohamed Athif


2 Answers

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.

like image 186
The Alpha Avatar answered Oct 06 '22 17:10

The Alpha


Use

@foreach($errors->getMessages() as $key => $error )
   Key: {{ $key }}
   Value: {{ $error[0] }}
@endforeach

if you var_dump the value of $error, you get an array:

array(1) { [0]=> string(13) "Successfully!" }

thus you need the key (0 in our case) of that array to access the message

like image 31
lewiscool Avatar answered Oct 06 '22 15:10

lewiscool