Understanding the sole() Query Builder Method

Published on by

Understanding the sole() Query Builder Method image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Visit Paragraph
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article
Use Google's Gemini AI in Laravel image

Use Google's Gemini AI in Laravel

Read article
PhpStorm is getting a brand new terminal image

PhpStorm is getting a brand new terminal

Read article
Six Essential Plugins for Visual Studio Code image

Six Essential Plugins for Visual Studio Code

Read article
Modularize Your Laravel Application With the Modular Package image

Modularize Your Laravel Application With the Modular Package

Read article
Handle Money Transactions in Eloquent with Laravel Wallet image

Handle Money Transactions in Eloquent with Laravel Wallet

Read article