Source: www.amitmerchant.com

The new findOr method in Laravel 9.x
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.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners