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

laracoft's avatar

Missing rows in Query Builder vs SQL

I extracted a long and complex query from Query Builder using ->toSql() and ran it manually to get this https://imgur.com/a/N7kSLAl

Then I used Laravel code to list the data in a browser, what happened was that:

  1. row3 was not present
  2. row5 and 6 was present (implying exact duplicates can returned)
  3. row100 was present

Any idea why row 3 could have disappeared?

0 likes
9 replies
Nakov's avatar
Nakov
Best Answer
Level 73

Do you use soft deletes on your model? Having deleted_at column in your table, Eloquent will automatically ignore those rows, unless you add withTrashed().

laracoft's avatar

@Nakov

Yes I do, but doesn't it filter out using SQL? Let me check.

laracoft's avatar

@nakov ok you are right, there is no sign of deleted_at anywhere in the SQL.

laracoft's avatar

@nakov

I added ->withTrashed() to my query, getting this Call to undefined method Illuminate\Database\Eloquent\Builder::withTrashed()

Nakov's avatar

@laracoft you said you are using eloquent. If that's right then it should be Model::withTrashed()->... if you use the query builder then you should just add ->orWhereNotNull('deleted_at') so in your SQL script in order to get the same results you should add the same check where deleted_at is null or is not null.

laracoft's avatar

@Nakov

Ok my bad, it's query builder. Does Laravel automatically filter out records with deleted_at for query builder as well?

Nakov's avatar

@laracoft no it does not. You can run ->toSql() on that and inspect why is it different then your custom SQL query. You are not sharing any code, so I don't know how to help.

laracoft's avatar

@Nakov

I would like to, but the raw query constructed by the query builder is 60+ lines long and involves multiple tables. It will almost certainly raise more questions than answers.

What puzzles me is why the raw query yields my desired output, but gives the wrong output when executed via code.

Let me try to dig a bit further and simplify the query if I can.

laracoft's avatar

@nakov

Thanks for your help, I just want to further add that:

  1. It was eloquent, however, once I started calling select and join etc, it became query builder, and thus withTrashed() did not work
  2. The query was really complex and there were multiple problems
  3. Nonetheless, withTrashed pointed me in the right direction eventually solving the issue

Please or to participate in this conversation.