dmattingley's avatar

Laravel not returning first record

Laravel isn't recognising the first record of anything I add.. ie

When I add a record to the database - $client = factory(\Client::class)->create(); then look at

  • dd($client); it has an id of 1 but if i try and any related records it says it doesn't exist;
  • dd(\Client::all()) returns an empty collection
  • \DB::table('clients')->get() shows the record (and deleted_at is null)

If i add a second record to the database with the factory above then

  • dd($client) works as expected with an id of 2
  • dd(\Client::all()) returns only the second collection
  • \DB::table('clients')->get() shows both records as expected.

This is the same over all models, not just \Client

0 likes
5 replies
dmattingley's avatar

This is happening throughout the app. So its not just on my factory->create methods, they were just an easy example.

ankitparmar372's avatar

You used soft delete for Client model? Check that because on eloquent they deleted_at while in DB query not included deleted_at.

1 like
dmattingley's avatar

I've been having a play, ::all() seems to be generating this sql

  • select * from "clients" where "clients"."id" != '1' and "clients"."deleted_at" is null which explains why its ignoring the first.

If I try something more like $clients = \Client::where('1','1'); it still appends "clients"."id" != '1' to the query:

  • select count(*) as aggregate from "clients" where "clients"."id" != '1' and "1" = '1' and "clients"."deleted_at" is null
dmattingley's avatar
dmattingley
OP
Best Answer
Level 5

Turns out the original developer has this little gem injecting into each query.

$query->where($this->table . '.id', '!=', 1); ... That was a wasted day.

Please or to participate in this conversation.