Laravel Eloquent : Relationship Inserting Related Models

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any Laravel Question?