skip to Main Content

I’m trying to use the cloneWithout method from the Laravel query builder but it has no effect.

Sample:

use AppModelsQuote;

$query = Quote::query()->select(['id', 'status', 'supplier_id'])->orderBy('id');

$cloned = $query->cloneWithout(['orders']);

return [
  $query->toRawSql(),
  $cloned->toRawSql()
];

Output:

[
    "select `id`, `status`, `supplier_id` from `quotes` order by `id` asc",
    "select `id`, `status`, `supplier_id` from `quotes` order by `id` asc",
]

I was expecting to get the out put as:

[
    "select `id`, `status`, `supplier_id` from `quotes` order by `id` asc",
    "select `id`, `status`, `supplier_id` from `quotes`",
]

2

Answers


  1. It seems cloneWithout is not working on Eloquent Builders and only works on Query Builder.

    Solution 1:
    Using DB Facade:

    ...
    use IlluminateSupportFacadesDB;
    
    ...
    
    $query = DB::table('quotes')->select(['id', 'status', 'supplier_id'])->orderBy('id');
    
    $cloned = $query->cloneWithout(['orders']);
    
    return [
        $query->toSql(),
        $cloned->toSql()
    ];
    

    If you insist on using the Quote model, You may want to consider trying these two options as well:
    Solution 2:

    Clone whole object using PHP’s clone and then add orderBy.

    $query = Quote::query()->select(['id', 'status', 'supplier_id']);
    
    $cloned = clone $query;
    
    $query->orderBy('id');
    
    return [
        $query->toSql(),
        $cloned->toSql()
    ];
    

    Solution 3 (Recommended):

    Convert your Eloquent Builder to Query Builder using toBase

    $query = Quote::query()->select(['id', 'status', 'supplier_id'])->orderBy('id')->toBase();
    
    $cloned = $query->cloneWithout(['orders']);
    
    return [
        $query->toSql(),
        $cloned->toSql()
    ];
    
    Login or Signup to reply.
  2. Just chain your $query variable with Laravel’s toBase() function and it will work.

    like below

    $cloned = $query->toBase()->cloneWithout(['orders']);
    

    You can read more about toBase() here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search