Understanding the sole() Query Builder Method

Tutorials

January 22nd, 2021

laravel-sole-featured.png

Laravel 8.23 introduces a sole() method on the query builder, which retrieves a single record but also has additional assertions.

Sole is useful when you need a single row from the query and assert the query only matches one record. It’s advantageous when you expect one record but want absolute assurance that only a single record exists. When more than one or less than one record exist, Laravel throws an exception.

We figured we’d demonstrate how to use it and what to expect from the three possible scenarios:

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

Quick Demo

Let’s create a quick demo app so you can follow along if you want and experiment.

First, create a Laravel project:

laravel new sole-demo
cd sole-demo

Next, create a model we can use to demonstrate how sole() works:

php artisan make:model -m Book

Finally, we’ll define the books database table for our model:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('summary');
            $table->dateTime('published_at')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

Don’t forget to make sure the fields we’ve created are fillable:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;

    /**
     * @var string[]
     */
    public $fillable = ['title', 'summary'];
}

Run the migration which we will use in the next section to experiment with the query builder:

php artisan migrate:fresh

You should now have a books table that we’ll use to demonstrate a few examples.

Using the sole() Method

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

use App\Models\Book;

Book::create([
    'title' => 'War of the Worlds',
    'summary' => 'Example summary'
]);

// All the records that match the query
Book::where('title', 'like', '%War%')->get();
/*
Illuminate\Database\Eloquent\Collection {#4264
 all: [
   App\Models\Book {#4209
     id: 1,
     title: "War of the Worlds",
     summary: "Example summary",
     published_at: null,
     created_at: "2021-01-21 22:14:29",
     updated_at: "2021-01-21 22:14:29",
   },
 ],
}
*/

// Get the first record in the query
// Even if the query has multiple matches, return the first one
Book::where('title', 'like', '%War%')->first();

/*
=> App\Models\Book {#4210
     id: 1,
     title: "War of the Worlds",
     summary: "Example summary",
     published_at: null,
     created_at: "2021-01-21 22:14:29",
     updated_at: "2021-01-21 22:14:29",
   }
*/

The get() and first() methods are fairly common in Laravel apps, however, sole() is useful when you expect and want to guarantee the existence of one and only one record:

Book::where('title', 'like', '%War%')->sole();
/*
App\Models\Book {#3647
  id: 1,
  title: "War of the Worlds",
  summary: "Example summary",
  published_at: null,
  created_at: "2021-01-21 22:14:29",
  updated_at: "2021-01-21 22:14:29",
}
*/

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

Book::where('title', 'like', '%The War')->sole();
// => Illuminate\Database\Eloquent\ModelNotFoundException

If we have more than a single record in the database table, we also get an exception, but this time it’s the MultipleRecordsFoundException:

// Create a second title with the word `War` in it.
Book::create([
    'title' => 'War and Peace',
    'summary' => 'Example summary'
]);

Book::where('title', 'like', '%War%')->sole();
// => Illuminate\Database\MultipleRecordsFoundException

Learn More

Hopefully, this quick walkthrough helped visualize what to expect when using sole() in Laravel 8 applications. The Laravel 8.23.0 release notes have more information and links to the pull requests if you’d like to see how sole() was implemented.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.