我有一个项目,如果我想访问partner/X
我会get property of non object
出错,因为我的合作伙伴比 X 少。
我的问题。如何告诉控制器,那if the result of the modelquery is empty, than throw a 404 error
?
我的代码到目前为止:
public function showPartner($id = 0){
//Only allow numerical values
if ($id > 0){
$partner = Partner::find($id);
if (empty($partner)){
return ???
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用abort()
助手:
abort(404);
Run Code Online (Sandbox Code Playgroud)
如果您愿意的话,abort_if()
还有。 abort_unless()
无论您选择哪一个,都可以向其传递所需的状态代码。
Laravel 有一个特定的方法。如果您使用findOrFail($id)
,它将抛出一个Illuminate\Database\Eloquent\ModelNotFoundException
,因此您无需自己抛出异常。
如果您的意思是“向用户显示 404 错误”而不是从字面上抛出异常,请捕获它并abort()
:
public function showPartner($id = 0){
//Only allow numerical values
if ($id > 0){
try {
$partner = Partner::find($id);
// do your work
}
catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
abort(404, "The Partner was not found");
}
}
}
Run Code Online (Sandbox Code Playgroud)
在此处阅读更多相关信息。
归档时间: |
|
查看次数: |
13057 次 |
最近记录: |