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

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners