Skip to main content
Category:

Inserting & Updating Related Models in Laravel

 

Eloquent provides convenient methods for adding new models to relationships. For example, perhaps you need to insert a new Comment for a Post model. Instead of manually setting the post_id attribute on the Comment, you may insert the Comment directly from the relationship's save method:

 

$comment = new App\Models\Comment(['message' => 'A new comment.']);

$post = App\Models\Post::find(1);

$post->comments()->save($comment);

 

Notice that we did not access the comments relationship as a dynamic property. Instead, we called the comments method to obtain an instance of the relationship. The save method will automatically add the appropriate post_id value to the new Comment model.

If you need to save multiple related models, you may use the saveMany method:

 

$post = App\Models\Post::find(1);

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

 

The save and saveMany methods will not add the new models to any in-memory relationships that are already loaded onto the parent model. If you plan on accessing the relationship after using the save or saveMany methods, you may wish to use the refresh method to reload the model and its relationships:

$post->comments()->save($comment);

$post->refresh();

// All comments, including the newly saved comment...
$post->comments;

 

If you would like to save your model and all of its associated relationships, you may use the push method:

$post = App\Models\Post::find(1);

$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';

$post->push();

 

In addition to the save and saveMany methods, you may also use the create method, which accepts an array of attributes, creates a model, and inserts it into the database. Again, the difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array:

$post = App\Models\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);

 

You may use the createMany method to create multiple related models:

$post = App\Models\Post::find(1);

$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

You may also use the findOrNewfirstOrNewfirstOrCreate and updateOrCreate methods to create and update models on relationships.

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook