Sergej Fomin
Sergej Fomin

Reputation: 2002

Laravel Query Builder use multiple times

Is it possible to save a query bulider and use it multiple times?

for example, I have a model 'Tour'.

I create a long query buider and paginate it:

$tour = Tour::where(...)->orWhere(...)->orderBy(...)->paginate(10);

For example, 97 models qualify for the above query. "Paginate" method outputs first 10 models qualifying for the query, but I also need to so some operations on all 97 models. I don't want to 'repeat myself' writing this long query 2 times.

So I want something like:

$query = Tour::where(...)->orWhere(...)->orderBy(...);

$tour1 = $query->paginate(10); 
$tour2 = $query->get();

Is that a correct way to do in Laravel? (my version is 5.4).

Upvotes: 3

Views: 1702

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

You can but it doesn't make any sense because every time a new query will be executed. So this code will work:

$query = Tour::where(...)->orWhere(...)->orderBy(...);
$tour1 = $query->paginate(10); 
$tour2 = $query->get();

But if you want to execute just one query, you'll need to use collection methods for ordering, filtering and mapping the data. You'll also need to create Paginator instance manually:

$collection = Tour::where(...)->orWhere(...)->orderBy(...)->get();
$tour1 = // Make Paginator manually.
$tour2 = $collection;
$sortedByName = $collection->sortBy('name');
$activeTours = $collection->where('active', 1);

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9853

You need to use clone:

$query = Tour::where(...)->orWhere(...)->orderBy(...);
$query1 = clone $query;
$query2 = clone $query;

$tour1 = $query1->paginate(10); 
$tour2 = $query2->get();

Upvotes: 3

Related Questions