Laravel Eloquent : Relationship Inserting Related Models


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.']);


You can save multiple models at once using the saveMany function:

$post = Post::find(1);

    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);

    'message' => 'This is a new comment message'