I have this code:
$subOffers = SubOffer::get()->where('offers_id', 1);
When I return $subOffers, I get 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 get 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 got n-1 keys.
How is this going? Why am I receiving an object instead of an array? This happens when Offers_id is greater than 1. Offers_id is the foreign key.
P粉1363562872024-01-04 09:37:25
Okay, I found the solution
$subOffers = SubOffer::where('offers_id', $id)->get();
Just I have to swap where with get
But I still don’t know, what’s going on? I want to know why this is happening.
P粉4045397322024-01-04 09:35:16
The get() method on eloquent returns a Laravel collection, i.e. anything you put after it, such as where() affects the resulting collection, see https://laravel.com/docs/9 . x/collections, a collection is an array-like object, but with a lot of functionality similar to database queries, but all in local memory.
If you have a where() method before get(), you are building a database query and the query will not be executed until get(). You will get different results because the query building and collection methods work similarly, but they perform different operations.