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();
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.