Laravel : Handle findOrFail( ) on Fail

后端 未结 6 1713
灰色年华
灰色年华 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:11

    Another option is to modify the default Laravel Exception Handler, found in app/Exceptions/Handler.php on the render() function I made this change:

    public function render($request, Exception $e)
    {
        if(get_class($e) == "Illuminate\Database\Eloquent\ModelNotFoundException") {
            return (new Response('Model not found', 400));
        }
        return parent::render($request, $e);
    }
    

    That way instead of getting a 500, I send back a 400 with a custom message without having to do a try catch on every single findOrFail()

提交回复
热议问题