Skip to main content
Quick Tip

Retrieve the Query Builder after filtering the results

To retrieve the Query Builder after filtering the results: you can use ->toQuery().

The method internally use the first model of the collection and a whereKey comparison on the Collection models.

// Retrieve all logged_in users
$loggedInUsers = User::where('logged_in', true)->get();
 
// Filter them using a Collection method or php filtering
$nthUsers = $loggedInUsers->nth(3);
 
// You can't do this on the collection
$nthUsers->update(/* ... */);
 
// But you can retrieve the Builder using ->toQuery()
if ($nthUsers->isNotEmpty()) {
$nthUsers->toQuery()->update(/* ... */);
}

Tip given by @RBilloir

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

[NEW] Building a Typical Laravel SaaS

11 lessons
1 h 36 min

How to Build Laravel 12 API From Scratch

28 lessons
1 h 21 min

Claude Code for Laravel Projects: Crash Course

8 lessons
48 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.