Suppose you have a Post
model with a hasMany
relationship with Comment
. You may insert a Comment
object related to a post by doing the following:
$post = Post::find(1);
$commentToAdd = new Comment(['message' => 'This is a comment.']);
$post->comments()->save($commentToAdd);
You can save multiple models at once using the saveMany
function:
$post = Post::find(1);
$post->comments()->saveMany([
new Comment(['message' => 'This a new comment']),
new Comment(['message' => 'Me too!']),
new Comment(['message' => 'Eloquent is awesome!'])
]);
Alternatively, there's also a create
method which accepts a plain PHP array instead of an Eloquent model instance.
$post = Post::find(1);
$post->comments()->create([
'message' => 'This is a new comment message'
]);