Search code examples
phparrayslaravelobjectlaravel-blade

Laravel $errors in Blade mystery


Can someone explain to me why sometimes I have to use $errors->all() and sometimes not? I'm struggling to find a unique solution for array of error and object $errors.

// View 1
@if (count($errors) > 0)
    @foreach($errors as $error)
        {{ $error }}<br>
    @endforeach
@endif

// View 2 that sometimes it crashes with:
// "Call to a member function all() on array"
@if (count($errors) > 0)
    @foreach($errors->all() as $error)
        {{ $error }}<br>
    @endforeach
@endif

Solution

  • $errors->all() using if you validate data via Validator or in the Request class. See this part of the documentation. Laravel share $errors variable as MessageBag class.

    $errors as array using if in the controller you return something like this:

    return back()->withErrors([
        'field1' => 'Error in the field 1'
    ]);
    

    In this case Laravel share $errors variable as array