php - Controller 中的 if else 语句在 Laravel 中没有响应

标签 php mysql laravel if-statement controller

我试图通过在我的 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。如果将该部分更改为 getfirst,您可能会得到所需的结果。

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 and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.

Documentation (向下滚动到“未找到异常”部分)

关于php - Controller 中的 if else 语句在 Laravel 中没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51061534/

相关文章:

php - 如何使 Laravel 的验证器 $rules 可选?

php - MySQL 与 LIKE 子句的错误?

php - WebMatrix 3 不显示 MySQL 数据库

mysql - 存储实体时出现 DataIntegrityViolationException

mysql - 我可以在mysql中将一个表的列值用作另一个表的表名吗?

php - Laravel eloquent updateOrCreate(), 只在创建时才做某事?

javascript - 拉维尔 : Different json output for the same query

php - 这是上传文件的好过滤器吗?

php - 如何从 html 表更新特定的 sql 行

MySQL - 来自一个查询的两条记录集,具有不同的顺序和限制