A minor release for Laravel 9.x dropped a few days ago and among lots of new features and improvements, this release has introduced a new method called findOr in the Eloquent Builder and Relations. So, before this release, Eloquent had the method called the findOrFail method which as its name suggests would throw a ModelNotFoundException exception if a model is not found.
To mitigate this, Laravel 9.x now has the findOr method. The findOr method works just like firstOr where it will return a single model instance or, if no results are found, execute the given closure.
User::findOr(1, fn () => throw new RuntimeException); User::findOr(1, fn () => abort(403)); User::findOr(1, fn () => 'return something'); As you can tell, it’s now pretty convenient to alter the response in case there aren’t any matching models.