Ricardinho
Ricardinho

Reputation: 609

Laravel blade "Call to a member function has() on array"

controller:

session(['errors' => ['email' => ['The email is invalid.']]]);
return view('auth.login');

blade:

@if ($errors->has('email'))
   <span class="help-block">
      <strong>{{ $errors->first('email') }}</strong>
   </span>
@endif

error:

Call to a member function has() on array

I have tried (object) before array, return view()->with() and much more!! But I always get this error!!

If possible I dont want to change the blade file!! Is there anyway to send that data from controller in the right way??

Upvotes: 0

Views: 2483

Answers (1)

Manpreet
Manpreet

Reputation: 2620

$errors returned by Validator is an instance of Illuminate\Support\MessageBag and not an array;

To replicate the usage: In your controller, you can:

use Illuminate\Support\MessageBag;

// Create a new MessageBag instance in your method.
$errors = new MessageBag;

// Add new messages to the message bag.
$errors->add('email', 'The email is invalid.');

return view('auth.login', ['errors' => $errors]);

I reckon you should use another variable name like $customErrors in your blade template, just to make sure you can use view('view')->withErrors($validator) in future if required, because withErrors pass variable $errors to view tempalte. https://laravel.com/docs/5.8/validation#working-with-error-messages

Upvotes: 4

Related Questions