Laravel : Handle findOrFail( ) on Fail

后端 未结 6 1878
灰色年华
灰色年华 2021-02-13 17:31

I am looking for something which can be like findOrDo(). Like do this when data not found. Something could be like

Model::findOrDo($id,function(){
   return \"Da         


        
6条回答
  •  没有蜡笔的小新
    2021-02-13 18:22

    By default, when you use an Eloquent model’s findOrFail in a Laravel 5 application and it fails, it returns the following error:

    ModelNotFoundException in Builder.php line 129:
    'No query results for model [App\Model]'.
    

    So to catch the exception and display a custom 404 page with your error message like "Ooops"....

    Open up the app/Exceptions/Handler.php file, and add the code shown below to the top of the render function:

    public function render($request, Exception $e)
    {
       if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) 
       {
          abort(404, 'Oops...Not found!');
       }
    
       return parent::render($request, $e);
    }
    

    Source: https://selftaughtcoders.com/from-idea-to-launch/lesson-16/laravel-5-findorfail-modelnotfoundexception-show-404-error-page/

提交回复
热议问题