I’m using Laravel 8. I would like to have a query, where all items from the users
table are listed twice, one with created_at column, and second with updated_at column. The result of this array should be in an ascending date order (mix of created_at and updated_at dates).
My table:
Expected result:
Zoey 2022-10-19 ...
Peter 2022-10-20 ...
Zoey 2022-10-24 ...
Peter 2022-10-31 ...
How to do that in Laravel 8?
2
Answers
First, create two queries:
Then merge the collections
And then you can sort them.
In order to accomplish this, you can use the
union()
method in Eloquent. Also, be sure to useselectRaw()
so you can alias the date columns asdate
. The union will need the columns to have the same name:The result would be a collection like this:
Then you can get the array from it using
->toArray()
:Edit: Another good solution by @aynber. That solution uses Query Builder. So it depends on your code style on which you use 🙂