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
A little later for the party, from laravel 5.4 onward, Eloquent Builder supports macros. So, I would write a macro (in a separate provider) like follows.
I can then do a retrieval as follows.
This will assign the first object of the result set if it is not empty, otherwise will adapt the behaviour I pass into the macro as a closure (throw
Illuminate\Database\Eloquent\ModelNotFoundException
in this case).For the case of a model also this would work, except that models always return the builder instance.
By default, when you use an Eloquent model’s
findOrFail
in a Laravel 5 application and it fails, it returns the following error: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:Source: https://selftaughtcoders.com/from-idea-to-launch/lesson-16/laravel-5-findorfail-modelnotfoundexception-show-404-error-page/
Another option is to modify the default Laravel Exception Handler, found in app/Exceptions/Handler.php on the
render()
function I made this change: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()
An alternative process could be to evaluate a collection instead. So,
I agree it isn't as elegant, a one-liner or as case specific as you or I might like, but aside from writing a try catch statement every time, it's a nice alternative.
as of Laravel v5.7, you can do this (the retrieving single model variation of @thewizardguy answer)