Laravel - Relationships - The Save Method
Eloquent provides convenient methods for adding new models to relationships. For example, perhaps you need to add a new comment to a post. Instead of manually setting the post_id
attribute on the Comment
model you may insert the comment using the relationship's save
method:
use App\Models\Comment;
use App\Models\Post;
$comment = new Comment(['message' => 'A new comment.']);
$post = Post::find(1);
$post->comments()->save($comment);
Note 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 = Post::find(1);
$post->comments()->saveMany([
new Comment(['message' => 'A new comment.']),
new Comment(['message' => 'Another new comment.']),
]);
The save
and saveMany
methods will persist the given model instances, but will not add the newly persisted 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;