Author

Inserting and Updating Related Models in Laravel

Image

by Samarth Sinha on 2017-05-29 08:55:15

The Save Method

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():

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

$post = App\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() 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():

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

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

The Create Method

In addition to the save() and saveMany()  you may also use the create(), 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\Post::find(1);

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

About the Author

  • avatar
    Samarth Sinha

    My name Samarth Sinha. I work on developing Web Applications using PHP and MySQL and in different frameworks of PHP like Laravel, CakePHP, CodeIgnitor and Smarty. In databases I have worked in MySQL and Postgres. I started this blog to share my knowledge to those who wants to start developing Web Applications using PHP.