'How to use Laravel API Resources with additional queries?
I have a database with the structure below;
(4677, 'Iceland', 'Torlakshofn', 63.8500000, -21.3666668, -9999.0),
(4678, 'Iceland', 'Stykkisholmur', 65.0666667, -22.7333336, 14.0),
(4679, 'Iceland', 'Olafsvik', 64.8833333, -23.7166672, 211.0),
(4680, 'Iceland', 'Eskifjordur', 65.0666667, -14.0166664, -9999.0),
(4681, 'Iceland', 'Vogar', 63.9666667, -22.3666668, 20.0),
(4757, 'India', 'Patna', 25.6000000, 85.1166687, 50.0),
(4758, 'India', 'Bhopal', 23.2666667, 77.4000015, 487.0),
(4759, 'India', 'Ludhiana', 30.9000000, 75.8499985, 243.0),
Which basically is a list of countries with their cities, but listed on one single table. Now, I would like to retrieve my resource collection like below;
[
{
id: 1,
country: 'Iceland',
locations: [
{
"id": 1,
"city": "City 1",
"longitude": "69.1833344",
"latitude": "34.5166667"
},
{
"id": 2,
"city": "City 2",
"longitude": "69.1833344",
"latitude": "34.5166667"
}
]
},
{
id: 2,
country: 'India',
locations: [
{
"id": 4,
"city": "City 1",
"longitude": "69.1833344",
"latitude": "34.5166667"
},
{
"id": 5,
"city": "City 2",
"longitude": "69.1833344",
"latitude": "34.5166667"
}
]
}
]
I couldn't figure out how to retrieve such a response using Laravel API Resources. Could anybody help me out here?
Solution 1:[1]
I don't think it's possible to have that result by using Laravel API Resources
I suggest using groupBy('country') to collect data of the same country.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali Jouadi |
