php - 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>
解决方案
当然这是一个错误,因为您试图访问非对象的属性。您的数组将有一个元素null
.
这是一个糟糕的设计,因为如果学生不存在,您不应该从一开始就返回视图。您应该抛出一些错误,可能是 HTTP 404。
幸运的是,Laravel 让这一切变得简单。Student::findOrFail($id);
当学生不存在时,您可以使用抛出异常。
当你的控制器只返回一个学生时,你在视图中循环遍历学生对我来说似乎很奇怪。如果由于某种原因您不想要 404,您总是可以通过 array_filter 运行 $outputs 以摆脱空值,或者当它为空时不将其添加到 $outputs 中。
推荐阅读
- angular - 是否有任何解决方案可以从请求标头中隐藏授权或隐藏令牌
- java - 使用 Cognito 时通过 AWS API Gateway Lambda 函数添加额外的 JWT 声明
- jquery - 如何在 Angular 7 中使用 FlipClock Js
- google-bigquery - 当目标表在 Bigquery 上具有覆盖首选项时,所有列都存在 NULLABLE 问题
- javascript - 在 Vuejs 方法中的 Javascript 中分配转换后的 `Base64` 值
- java - CN1:从多按钮的第二行更改文本颜色
- javascript - 如何以表格格式显示当前通过 js 在页面中显示的数据?(我已经从上一页获得了输入)
- javascript - 如何使用 Readmore jquery 插件显示 Read less 默认值
- javascript - 带有条件的甜蜜警报输入
- node.js - req.flash 不显示消息