Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

misagh's avatar

Clone and chain issue in laravel query builder and queues

Please consider my class constructor :

public function __construct(User $query = null)
{
    $this->query = $query ?: (new User())->getQuery();
}

I have a method like this :

public function getNullActivityUsers()
{
    $query = clone $this->query;

    $query->whereNull('activity');

    return $query->get();
}

When I call this method, the sql query will be this :

select * from `users` where `activity` is null

But when I push this method into laravel queue, the query will be this :

select * from `users`

In fact, the chaining method of whereNull would not be called in that method. I should change the method to this version:

public function getNullActivityUsers()
{
    $query = clone $this->query;

    $query = $query->whereNull('activity');

    return $query->get();
}

This will do the trick : $query = $query->whereNull('activity');

But I want to know, why laravel acts differently in this case. Because if I test the method outside the queue, the chaining will be there. But if I run it throw queue, it will get other result.

(( Imagine that I should use that clone always. ))

0 likes
1 reply
misagh's avatar

Please give me an answer. Thanks

Please or to participate in this conversation.