Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Update or Create Relationships

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'];
}
like image 523
Miguel Stevens Avatar asked Dec 24 '22 00:12

Miguel Stevens


1 Answers

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.

like image 78
D Malan Avatar answered Jan 05 '23 19:01

D Malan