我试图通过在我的 Controller 中使用此方法来阻止登录用户访问某些段落异常,用户在 NextofKin 表中有他的信息
public function checkValidTenant($tenant_id){
$check = NextOfKin::where('tenant_id', '=', $tenant_id)->findOrFail('tenant_id');
return $check;
}
在显示该页面的方法中,我添加了以下代码进行限制
if($this->checkValidTenant(\Auth::user()->id)){
$rents = RentDue::where('tenant_id', '=', \Auth::user()->id)->get();
return view('/tenant/rent', compact('rents'));
}else{
return redirect()->route('tenant/profile');
}
我也这样试过
if($this->checkValidTenant(\Auth::user()->id) === true){
$rents = RentDue::where('tenant_id', '=', \Auth::user()->id)->get();
return view('/tenant/rent', compact('rents'));
}else{
return redirect()->route('tenant/profile');
}
这是路线
Route::get('rent', 'TenantController@rent');
问题是当我尝试使用满足条件的登录用户访问页面时,它会抛出以下错误
Sorry, the page you are looking for could not be found.
但是我注意到只有当我取消这个限制时这个页面才会显示。我该如何解决这个问题?
最佳答案
findOrFail
在找不到记录时将抛出 404。如果将该部分更改为 get
或 first
,您可能会得到所需的结果。
public function checkValidTenant($tenant_id){
$check = NextOfKin::where('tenant_id', '=', $tenant_id)->first();
return $check;
}
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The
findOrFail
andfirstOrFail
methods will retrieve the first result of the query; however, if no result is found, aIlluminate\Database\Eloquent\ModelNotFoundException
will be thrown.
Documentation (向下滚动到“未找到异常”部分)
关于php - Controller 中的 if else 语句在 Laravel 中没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51061534/