Home / Snippets / How to Save Multiple Records at Once in Laravel Eloquent
How to Save Multiple Records at Once in Laravel Eloquent cover

How to Save Multiple Records at Once in Laravel Eloquent


2 years ago


Sometimes you might need to save multiple records at once and you can do so by using the "saveMany()" method or the "createMany()" method available to each of the Eloquent model relation.

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. 

$post = Post::first();

  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.

$post = Post::first();

  ['title' => 'Comment 1'],
  ['title' => 'Comment 2'],
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.






Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this