Php 在许多控制器中重复404代码:Laravel 5.2

Php 在许多控制器中重复404代码:Laravel 5.2,php,laravel-5,laravel-5.2,Php,Laravel 5,Laravel 5.2,我有以下代码 private function GetCountry($CountryID) { $Country = \App\Models\CountryModel ::where('CountryID', $CountryID) ->where('IsPredefined', false) ->first(); if($Country == null) {

我有以下代码

private function GetCountry($CountryID) {
    $Country = \App\Models\CountryModel
                ::where('CountryID', $CountryID)
                ->where('IsPredefined', false)
                ->first();
    if($Country == null) {
        \App::abort(404);
        return;
    }
    return $Country;
}
添加If条件以确保用户是否正在尝试查询字符串,其关联记录在数据库中不存在。如果我删除了if条件检查,我会在Blade中得到以下错误

正在尝试获取非对象的属性

根据控制器的不同,用不同的模型定义相同的功能

问题:我可以减少代码吗?我想保留404错误

为什么不使用它来为您进行检查

如果未找到结果,将引发Illumb\Database\Eloquent\ModelNotFoundException

如果未捕获异常,404 HTTP响应将自动发送回用户,因此在使用以下方法时,无需编写显式检查以返回404响应: