Did you try flatten ?
Apr 30, 2018
7
Level 5
Eloquent with hasMany relationship to single column strings array
Hi guys! I'm finishing a mobile app and providing an API through Laravel, everything is awesome but I struggle with one little problem. I have 3 entities: A Theme has many Items and a Theme belongs to a Language. I'm requesting my database with this inside my controller's action:
return Theme::whereHas('language', function ($query) use ($abbreviation) {
$query->where('abbreviation', '=', $abbreviation);
})->with(['items' => function ($query) {
$query->get()->pluck('item')->toArray();
}])->get();
Even with the pluck method, my API still returns an array of objects:
[
{
"id": 5,
[...]
"items": [
{
"item": "item 1..."
},
{
"item": "item 2..."
}
]
}
]
I would like to transform the array into a strings array :
"items": [
"item 1", "item 2"
]
Am I doing it the wrong way? Thanks :)
Please or to participate in this conversation.