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

successdav's avatar

Query Builder returning the wrong data

I expect this code to return just 3 results (the 3 unpublished posts) but it returns everything in the db::table.


    protected function draft()
    {
        return $this->builder->wherePublished(false);
    }

    protected function q($q)
    {
        return $this->builder->where('title', 'LIKE', '%' . $q . '%')
                    ->orWhere('body', 'LIKE', '%' . $q . '%');
    }   

and when I look into the sql that is about to be executed using the toSql() method here is what I get.

"select * from `posts` where (`published` = ? and `title` LIKE ? or `body` LIKE ?) and `posts`.`deleted_at` is null"

I have used this query and Navicat to query the database and I get the same problem, it retrieves everything in the table not considering if the record is published or not.

0 likes
3 replies
MichalOravec's avatar
Level 75
protected function q($q)
{
    return $this->builder->where(function ($query) use ($q) {
        $query->where('title', 'LIKE', "%{$q}%")->orWhere('body', 'LIKE', "%{$q}%");
    });
}

Docs: https://laravel.com/docs/8.x/queries#logical-grouping

You should always group orWhere calls in order to avoid unexpected behavior when global scopes are applied.

1 like
successdav's avatar

wow. Thanks. I will give that a read right away.

Please or to participate in this conversation.