Closed nekooee closed 3 years ago
+1
Totally depends on the way you are generating that response. In general $model->translations
is a default Laravel relationship that contains all translation models - so you can add them to your JSON response however you want. I recommend an eloquent API resource class.
Thank you for your response. The thing is that we want to translations will come with keyBy('locale')
You can do this in your API resource. You get a collection of translation models - so a quick way would be something like:
$model->translations->keyBy('locale')->map->only('title', 'content');
The code isn't tested but should show one way to do it - it's by far not the best/cleanest way to do, but should work. 😉
That's works if I set a separate variable, unfortunately translations attribute can't be overrided.
It doesn't have to be overridden!?
Your full JSON would be something like:
return response()->json([
'id' => $model->id,
'slug' => $model->slug,
'translations' => $model->translations->keyBy('locale')->map->only('title', 'content'),
]);
I used this method in the model before you answered. I do not know how optimal it is. Although it works properly:
protected $appends = [ 'translation_arrays'];
public function getTranslationArraysAttribute()
{
$title = $this->translations()->pluck('title', 'locale');
$content = $this->translations()->pluck('content', 'locale');
return ['title' => $title, 'content' => $content];
}
This issue is stale because it has been open 21 days with no activity. Remove stale label or comment or this will be closed in 7 days
how to get array for all translation with model? example: all()->getTranslationsArray()
I need to get a translation for my post model in the array.
like this:
please help me.