Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel cloning query string

Tags:

php

laravel

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

like image 710
Bri Avatar asked Dec 23 '14 17:12

Bri


2 Answers

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

like image 56
mopo922 Avatar answered Oct 31 '22 16:10

mopo922


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

like image 25
Nazareno Lorenzo Avatar answered Oct 31 '22 18:10

Nazareno Lorenzo