首页 > 解决方案 > laravel find() 返回空刀片文件时返回错误

问题描述

当模型不为空时,我尝试将模型传递给 view.blade,刀片文件运行时没有错误,但如果模型为空,刀片文件运行错误,这是我的代码

//StudentController code

public function viewstudent($id)
{
   $student = Student::find($id);
   $outputs = array($student);

   return view('student',['students'=>$outputs]);
}


//student.blade.php  code

<table id="myTable">

@foreach ($students as $student)    

<tr>
<td>{{$student->studentname}}</td>
<td>{{$student->studentlevel}}</td>
<td>{{$student->studentgender === 1 ?'Male':'Female'}}</td>
<td>{{$student->studentbirthdate}}</td>
<td>{{$student->studentnotes}}</td>
<td>{{$student->created_at}}</td>
<td>{{$student->updated_at}}</td>

</tr>
@endforeach

</table>

标签: phplaravel

解决方案


当然这是一个错误,因为您试图访问非对象的属性。您的数组将有一个元素null.

这是一个糟糕的设计,因为如果学生不存在,您不应该从一开始就返回视图。您应该抛出一些错误,可能是 HTTP 404。

幸运的是,Laravel 让这一切变得简单。Student::findOrFail($id);当学生不存在时,您可以使用抛出异常。


当你的控制器只返回一个学生时,你在视图中循环遍历学生对我来说似乎很奇怪。如果由于某种原因您不想要 404,您总是可以通过 array_filter 运行 $outputs 以摆脱空值,或者当它为空时不将其添加到 $outputs 中。


推荐阅读