6

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'];
}
Miguel Stevens
  • 8,631
  • 18
  • 66
  • 125

1 Answers1

14

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.

D Malan
  • 10,272
  • 3
  • 25
  • 50
  • I suppose this has to go in a foreach loop? to loop over the translations I'm receiving with the request? thank you. – Miguel Stevens Mar 12 '19 at 09:12
  • There's a `createMany` (https://laravel.com/docs/5.7/eloquent-relationships#the-create-method) method, but it doesn't look like there's something like a `updateOrCreateMany` method. – D Malan Mar 12 '19 at 09:15
  • @DelenaMalan May be you are searching for something like https://gist.github.com/tonila/26f6a82c4dbe63d93b22ac67eaee2d6d – Prafulla Kumar Sahu Mar 12 '19 at 10:27