Prerequisite For Saving Multiple Records
Do note that you need to have "hasMany()" relationship in order to do so. For example, imagine having a Post that has many Comments.
<?php # your post model class Post extends Model { # your other codes here public function comments() { return $this->hasMany(\App\Models\Comments::class); } }
Laravel saveMany() Code Example
The save many accepts multiple arrays of the relationship instance. In the case of this example, it will be the comments.
<?php $post = Post::first(); $post->comments()->saveMany([ new Comment(['title' => 'Comment 1']), new Comment(['title' => 'Comment 2']), ]);
The code above will save 2 comments at the same time for the first post.
Laravel createMany() Code Example
The other way is to use the createMany() method and you can just pass in the data as an array as follows.
<?php $post = Post::first(); $post->comments()->createMany([ ['title' => 'Comment 1'], ['title' => 'Comment 2'], ]);
Leave a reply