Laravel Eloquent's where method only returns an array of the first record in the database
P粉966979765
P粉966979765 2024-01-03 10:53:43
0
2
516

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粉966979765
P粉966979765

reply all(2)
P粉136356287

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粉404539732

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template