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

Duplicate 404 Code in many Controllers: Laravel 5.2

我有以下代码。

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 中收到以下错误。

Trying to get property of non-object

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

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

为什么不使用 firstOrFail(),它会为您进行检查

if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown

If the exception is not caught, a 404 HTTP response is automatically sent back to the user, so it is not necessary to write explicit checks to return 404 responses when using these methods: