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.

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
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Add Comments to your Laravel Application with the Commenter Package image

Add Comments to your Laravel Application with the Commenter Package

Read article
Laravel Advanced String Package image

Laravel Advanced String Package

Read article
Take the Annual State of Laravel 2024 Survey image

Take the Annual State of Laravel 2024 Survey

Read article
Upload Files Using Filepond in Livewire Components image

Upload Files Using Filepond in Livewire Components

Read article
The Best Laravel Tutorials and Resources for Developers image

The Best Laravel Tutorials and Resources for Developers

Read article
Introducing Built with Laravel image

Introducing Built with Laravel

Read article