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.

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

Tip given by @RBilloir

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord