I have an Item model, that has ItemTranslations, I'm receive a Request with the Item I'm updating and the translations for that Item.
Now some of those translations will already be in the database (they have their own id), and some of them will be new. Is there a clean way to go about this?
In pseudo: Update the Item with this request, for each Translations you find in this request, update the translation relation if it exists, else create it for this Item.
This is the layout of my Item.
class Item extends Model
{
protected $fillable = ['menu_id', 'parent_id', 'title', 'order', 'resource_link', 'html_class', 'is_blank'];
public function translations()
{
return $this->hasMany(MenuItemTranslation::class, 'menu_item_id');
}
}
This is the ItemTranslation
class ItemTranslation extends Model
{
protected $table = 'item_translations';
protected $fillable = ['menu_item_id', 'locale', 'name', 'order', 'description', 'link', 'is_online'];
}
You could use the updateOrCreate
method on the translations()
relationship. For example:
$item->translations()->updateOrCreate([
'name' => $translation['name'],
// Fields that should be used to find an existing record.
], [
'description' => "New description",
// Fields that should be updated.
]);
The first argument is the data that you want Eloquent to look up the translation
by and second argument is the data that you want to be updated.
Both arguments will be used to create a new translation
when an existing one couldn't be found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With