Backend Development 7 min read

Inserting and Updating Related Models with Laravel Eloquent

This article explains how to add, update, and manage related Eloquent models in Laravel—including saving single or multiple related records, using associate/dissociate for belongsTo relations, and handling many‑to‑many pivots with attach, detach, sync, toggle, and timestamp propagation.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Inserting and Updating Related Models with Laravel Eloquent

Insert & Update Related Models

Eloquent provides convenient methods for adding related models. For example, to add a new Comment to a Post you can create the comment instance and call the save method on the comments relationship, which automatically fills the post_id foreign key.

$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);

To save multiple related models you can use saveMany :

$post = App\Post::find(1);
$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.'])
]);

Creating Related Models

Besides save and saveMany , you can use create which accepts an attribute array and persists the model in one step. create works with plain arrays, while save expects a full model instance.

$post = App\Post::find(1);
$comment = $post->comments()->create(['message' => 'A new comment.']);

You can also use createMany to create several related models at once:

$post = App\Post::find(1);
$post->comments()->createMany([
    ['message' => 'A new comment.'],
    ['message' => 'Another new comment.']
]);

Updating a belongsTo Relationship

When updating a belongsTo relation, use associate to set the foreign key on the child model, and dissociate to null it.

$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();

$user->account()->dissociate();
$user->save();

Many‑to‑Many Relationships

Attach / Detach

Use attach to insert a record into the pivot table and detach to remove it. Both methods accept an ID or an array of IDs, and you can pass additional pivot data.

$user = App\User::find(1);
$user->roles()->attach($roleId);
$user->roles()->attach($roleId, ['expires' => $expires]);
$user->roles()->detach($roleId);
$user->roles()->detach(); // remove all

Sync

sync replaces the pivot table records with the given ID array, removing any IDs not present. syncWithoutDetaching adds new IDs without removing existing ones.

$user->roles()->sync([1, 2, 3]);
$user->roles()->syncWithoutDetaching([1, 2, 3]);

Toggle

toggle will attach IDs that are not currently attached and detach those that are.

$user->roles()->toggle([1, 2, 3]);

Saving Pivot Data

You can pass extra data when saving a related model with save on a many‑to‑many relation.

App\User::find(1)->roles()->save($role, ['expires' => $expires]);

Updating Existing Pivot Records

Use updateExistingPivot to modify a pivot row.

$user->roles()->updateExistingPivot($roleId, $attributes);

Updating Parent Timestamps

When a child model belonging to a parent (e.g., Comment belongs to Post ) is updated, you can automatically touch the parent’s updated_at timestamp by defining a $touches property on the child model.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $touches = ['post'];

    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

Now updating a comment will also update the related post’s updated_at field, helping with cache invalidation.

$comment = App\Comment::find(1);
$comment->text = 'Edit to this comment!';
$comment->save();
backendDatabaseORMPHPLaravelEloquentRelationships
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.