Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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
CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and more

Visit CodeRabbit
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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
NativePHP logo

NativePHP

Build rich mobile apps across iOS and Android from a single Laravel codebase. This changes everything!

NativePHP
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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 Multi-tenant 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

The latest

View all →
Laravel Nightwatch - Deep monitoring & insights, no matter where you deploy. image

Laravel Nightwatch - Deep monitoring & insights, no matter where you deploy.

Read article
Filament v4 Beta - Feature Overview image

Filament v4 Beta - Feature Overview

Read article
AnyCable Laravel Broadcaster image

AnyCable Laravel Broadcaster

Read article
Parse Localized Numbers with Laravel's Number Class image

Parse Localized Numbers with Laravel's Number Class

Read article
Manage Taxonomies, Categories, and Tags in Laravel image

Manage Taxonomies, Categories, and Tags in Laravel

Read article
Extract Arrays from Any Data Type with Laravel's Arr::from Method image

Extract Arrays from Any Data Type with Laravel's Arr::from Method

Read article