首页 > 解决方案 > Laravel 刀片“调用数组上的成员函数 has()”

问题描述

控制器:

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

刀:

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

错误:

调用数组上的成员函数 has()

我在数组之前尝试过 (object),return view()->with() 等等!但我总是得到这个错误!

如果可能的话,我不想更改刀片文件!反正有没有以正确的方式从控制器发送数据?

标签: phplaravellaravel-blade

解决方案


Validator 返回的 $errors 是 Illuminate\Support\MessageBag 的一个实例,而不是一个数组;

要复制用法:在您的控制器中,您可以:

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]);

我认为您应该在刀片模板中使用另一个变量名称,例如 $customErrors ,以确保将来可以在需要时使用 view('view')->withErrors($validator) ,因为 withErrors 将变量 $errors 传递给查看模板. https://laravel.com/docs/5.8/validation#working-with-error-messages


推荐阅读