Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : Handle findOrFail( ) on Fail

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 "Data not found";
});

Is there any similar thing in laravel that I can do this elegantly and beautifully ?

*I tried googling but could not find one

like image 883
cjmling Avatar asked Oct 07 '15 09:10

cjmling


2 Answers

use Illuminate\Database\Eloquent\ModelNotFoundException;

// Will return a ModelNotFoundException if no user with that id
try
{
    $user = User::findOrFail($id);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
    dd(get_class_methods($e)); // lists all available methods for exception object
    dd($e);
}
like image 100
Meisam Mulla Avatar answered Sep 20 '22 14:09

Meisam Mulla


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/

like image 27
Josh D. Avatar answered Sep 16 '22 14:09

Josh D.