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

Amit Merchant

A blog on PHP, JavaScript, and more

The query builder's sole() method to validate multiple records in Laravel 8.x

With the latest release minor of Laravel, i.e. v8.23.0, a really interesting method has been introduced in Laravel’s query builder for situation where you want to get the only record for the matching criteria. But if there are more records for this criteria, there should be some sort of exception.

The method is called sole(). Let’s understand it in detail.

The sole() method

The sole() is been proposed in this PR by Mohamed Said. The method is inpired by Django’s get() and Rails’ .sole and find_sole_by methods.

Here’s how this method works.

try {
    $order = Order::where('invoice_number', '#INV12345')->sole();
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    // order not found
} catch (Illuminate\Database\Eloquent\MultipleRecordsFoundException $e) {
    // multiple records found
}

As you can tell, the query builder’s sole() method will return the only record that matches the criteria, if no records found a NoRecordsFoundException will be thrown, and if multiple records were found a MultipleRecordsFoundException will be thrown.

This method can proved to be useful when you need a single row, but also want to assert that there aren’t multiple rows matching the condition; especially when database constraints aren’t enough (such as Unique indexes in MySQL) or are impractical.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), 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?

Buy me a coffee

👋 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?