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
method:
$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
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\Post::find(1);
$post->comments()->saveMany([
new App\Comment(['message' => 'A new comment.']),
new App\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;
Recursively Saving Models & Relationships
If you would like to save
your model and all of its associated relationships, you may use the push
method:
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();