Is it possible to clone a query string so I can write it once and make alterations a long the way without affection other results?
$query = DB::table('users')
->where('id', '=', '123');
$queryGet = $query;
$queryPaginate = $query;
$queryCount = $query;
if(Input::has('get'))
$queryGet = $queryGet->get();
if(Input::has('paginate'))
$queryPaginate = $queryPaginate->paginate(25);
if(Input::has('count'))
$queryCount = $queryCount->count(DB::raw('Distinct users.*'));
Because right now, the paginate will alter the first get().
Thanks
You had the vocabulary exactly right :) In PHP5+, try cloning:
<?php
$queryGet = clone $query;
$queryPaginate = clone $query;
$queryCount = clone $query;
http://php.net/manual/en/language.oop5.cloning.php
Mopo922 answer is the right way to do this on Laravel >= 4.1. But, in previous versions, the query doesn't "deep clone", and would produce unexpected results, as the main query is stored in a child Query
object, not in the mail Builder
.
To avoid this bug, you can use:
$newClone = new \Illuminate\Database\Eloquent\Builder(clone $builder->getQuery());
You can see this bug/fix story on: https://github.com/laravel/framework/issues/1336
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With