How to use sole() query builder in Laravel 8.23 ?

Updated 15 May 2023

Introduction

With the release of Laravel 8.23,  ‘sole()’ method in laravel query builder is introduced, which retrieves a single record but has additional assertions.

Sole is beneficial once you need one row from the query and assert the query only matches one record. It’s advantageous once you expect one record but want absolute assurance that only one record exists. When quite one or but one record exist, Laravel throws an exception.

In order to make it more clear, Let’s check it out how we can use sole() method in different scenarios.
Let’s take 3 different scenarios here:

  1. One record that matches the query.
  2. No records that matches the query.
  3. More than one record that matches the query.

How to use the sole() method ?

First let’s create a Laravel App app:

Now we need to create a Model:

Now we need to Bagisto database table for our model:

Now Run the Migrate command:

Using Sole method

To experiment with sole(), we’ll use the php artisan tinker command to make records and query the database. First up, let’s see what happens once we use the standard first() or get() methods:

The get() and first() methods are fairly common in Laravel apps, however, sole() is beneficial once you expect and need to ensure the existence of 1 and just one record:

If we don’t have a record within the database table, we will expect the ModelNotFoundException thrown:

If we’ve quite one record within the database table, we also get an exception, but this point it’s the MultipleRecordsFoundException:

Sources:
Laravel’s Site
Laravel News

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home