Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

$book = Book::findOrFail(1);

And eventually, a 404 HTTP response would be sent back to the client. Now, this could be fine for some scenarios but as you can tell, it’s not very much customizable instead of just failing and returning a default 404 HTTP response.

To mitigate this, Laravel 9.x now has the findOr method.

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. The value returned by the closure will be considered the result of the method.

Here are some examples that are directly taken from the PR.

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.

On top of this, you could also specify the columns that you want to retrieve as the second argument in form of an array like so.

$book = Book::findOr(1, ['name', 'author'], function () { 
    // do something
});

Works with Relationships

The method also works with HasMany, HasManyThrough, BelongsToMany, MorphMany, and MorphToMany relations seamlessly.

$user->posts()->findOr(1, fn () => '...');
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?