Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Cloning queries in Laravel

Reusing database queries is a common practice to maintain clean, DRY (Don’t Repeat Yourself) code and ensure consistency across your application.

With Laravel, you have a host of options to reuse queries. For instance, you can use query scopes (local and global), repositories, traits, or custom collections to achieve this.

But there exists a rather undocumented method in Laravel’s query builder called clone that allows you to clone a query on the fly.

Here’s how it works.

$allUsers = User::query()
                    ->where('created_at', '<=', now()
                    ->subMonths(3));

$verifiedUsers = $allUsers
                    ->clone()
                    ->whereNotNull('email_verified_at')
                    ->get();

$unverifiedUsers = $allUsers
                    ->clone()
                    ->whereNull('email_verified_at')
                    ->get();

As you can tell, you would write a base query that has all the common conditions that you expect to be applied to all the cloned queries.

Next, you would clone the query and apply the conditions that you want to be specific to the cloned query. In the example above, we clone the $allUsers query and apply the condition that we want to be specific to the $verifiedUsers query that will fetch all the users that have verified their email addresses. Similarly for unverified users as well.

If, for some reason, you’re using orderBy on your base query and you want to change the order of the cloned query, you can use the reorder method on the cloned query as well.

$allUsers = User::query()->orderBy('id', 'desc');

$verifiedUsers = $allUsers
                    ->clone()
                    ->whereNotNull('email_verified_at')
                    ->reorder('id', 'asc')
                    ->get();
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?