Home > Net >  Laravel Eloquent returns Array only on first record in database (`where` method)
Laravel Eloquent returns Array only on first record in database (`where` method)

Time:07-10

I have code like this:

$subOffers = SubOffer::get()->where('offers_id', 1);

And when i return $subOffers i got an array like this.

[{"id":1,"offers_id":"1","price":"123.0","start_date":"2022-07-23","stop_date":"2022-07-24","additional_info":"r832ufr803yw98fhew98f8h93wq"}]

But when i change 1 to 2 or 3 or 4 or ... i got an object like this.

{"3":{"id":4,"offers_id":"4","price":"12,341","start_date":"2022-07-10","stop_date":"2022-07-13","additional_info":null}}

in this case i changed it to 4 and I got n-1 key.

What's going on here? Why do I receive an object instead of array? It happens when the offers_id is above 1. Offers_id is a foreign key.

CodePudding user response:

Okay, I found a solution

$subOffers = SubOffer::where('offers_id', $id)->get();

just I had to swap where with get

But still I don't know, what's going on here? I want to know, why is this happened.

CodePudding user response:

get() method on eloquent returns a laravel collection, anything you put after that, e.g. where(), is affecting the generated collection see https://laravel.com/docs/9.x/collections, collection is an object similar to an array, but with a large amount of functions similar to database queries but all is in local memory.

If you have where() method before the get(), you are building a database query and it is not executed until the get(). You are getting different results because query building and collection methods work in similar ways but they are doing different things.

  • Related