当我按城市名称搜索这是我的数据库表中找到,它会显示的结果,但是当我通过未知的城市,是不是在我的数据库表进行搜寻它说 - 无查询结果的模型[应用程序\城市。我正在分享你的代码和截图see error screenshot实际上我想重定向到401页如果在我的数据库表中找不到该城市
这是我的路线
路线::得到( '老师的作业按城市/ {城市}', 'TeacherJobsController @ by_location');
这是我的功能
公共职能by_location($ LOCATION_ID = ''){
$data= array();
$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();
$items= Subject::orderBy('id','asc')->get();
$data['location']=$location;
//$subjects = [''=>'Select Subject'] + Subject::lists('subject_title','id')->toArray();
//$city = [''=>'Select City'] + City::lists('name','id')->toArray();
$active_class ='Select Subject to see job Openings';
return view('frontend.teacherjobs.by_location',compact('active_class','data','items'));
}
那是因为你正在使用firstOrFail()
方法,如果命名的话,如果没有通过抛出将被视为“无查询结果模型...”消息的异常而导致失败。
如果你想它不失败,您可以:
firstOrFail()
替换first()
方法您可以通过修改Illuminate\Database\Eloquent\ModelNotFoundException
Exception的处理方式来处理这种错误。在App\Exceptions\Handler
类中,将render方法更改为如下所示
public function render($request, Exception $exception)
{
if($exception instanceof ModelNotFoundException){
return redirect("/error_page", 401)->with('error', $e->getMessage());
}
return parent::render($request, $exception);
}
在重定向中你必须放置你想要重定向的路径,我把/error_page
仅用于示例目的。您可以了解更多关于Error Handling”
不要忘记像这样的use Illuminate\Database\Eloquent\ModelNotFoundException;
导入ModelNotFoundException
替换此:
$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();
有了这个:
$location = City::where('slug',$location_id)->where('status','1')->first();
添加到Elias Soares的答案,这是因为如果firstOrFail不返回结果,laravel会生成“Illuminate \ Database \ Eloquent \ ModelNotFoundException”异常。
参考:https://laravel.com/docs/5.8/eloquent#retrieving-single-models
要如何处理这个异常是高达你。如果使用firstOrFail - >到第一()溶液
在用first替换firstOrFail之后,你会得到错误:“试图获取非对象的属性”,这是因为你的查询没有提取任何东西,因此它没有属性。为此,您可以检查查询结果。
$location = City::where('slug',$location_id)->where('status','1')->first();
!empty($location->attribute)?$location->attribute:null;