John Davidson

php - Why is one function returning an array and the other one an object in Laravel

0 comments
Message:


I have two Laravel functions that use Eloquent to retreive information from the DB(Postgres) which are virtually the same except that the where in one is a greater or equal than and the other one is less than (dates)


First function:


events = Event::join('cat_status_event', 'event.status', '=', 'cat_status_event.id_cat_status_event')
->join('place', 'event.place', '=', 'place.id_place')
->take(50)
->get(['event.name','place.name as place', 'cat_status_event.description as status'])
->where('start', '>=', date('Y-m-d'));

And is returning this response (an array):


[
{
"name": "Christmas",
"start": "2020-12-24 17:29:23",
"status": "OK"
},
{
"name": "Thanksgiving",
"start": "2021-11-26 01:19:30",
"status": "OK"
}
]

And the second function:


events = Event::join('cat_status_event', 'event.status', '=', 'cat_status_event.id_cat_status_event')
->join('place', 'event.place', '=', 'place.id_place')
->take(50)
->get(['event.name','place.name as place', 'cat_status_event.description as status'])
->where('start', '<', date('Y-m-d'));

And is returning this json (an object):


{
"2": {
"name": "Birthday",
"start": "2020-11-21 01:17:07",
"status": "OK"
},
"3": {
"name": "Anniversary",
"start": "2020-11-21 01:17:07",
"status": "OK"
}
}

I want both functions to return arrays (like the first one), and the only difference between theme is at the where statement at the end



My Answer:
>where('event.start_date', '>=', $date)->get();_Second function:_events = Event::join('cat_status_event', 'event.status', '=', 'cat_status_event.id_cat_status_event')_ ->where('event.end_date', '<', $date)->get();_The issue you are facing is not related to Laravel or Eloquent specifically, but rather how the data is being retrieved from the database. In Laravel, when you use the `get()` method on a query builder instance, it returns a collection of objects by default. However, if you want to retrieve the data as an array instead of an object, you can use the `toArray()` method._In your case, if you want the data returned by the second function to be an array instead of an object, you can modify the code like this:_events = Event::join('cat_status_event', 'event.status', '=', 'cat_status_event.id_cat_status_event')_ ->where('event.end_date', '<', $date)->get()->toArray();_This will ensure that the data returned by the second function is in array format.

Rate this post

4 of 5 based on 5545 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us