Posts Learn Components Snippets Categories Tags Tools About
/

How to Bulk Insert Using Eloquent ORM In Laravel

Learn how to perform bulk insert in Laravel using Eloquent ORM the easy way

Created on Oct 24, 2021

10527 views

Sometimes you might need to bulk insert some data in Laravel and the easiest way is to make use of Eloquent ORM. Imagine having "Post" model and you want to insert 2, 5, 10, or even 20 at a time, you can write your code like below.

Laravel Bulk Insert Using Eloquent ORM


You can pass in an array to the "insert" method and within the array which contains another array of data.
<?php

use App\Models\Post;

Post::insert([
    ['name'=>'Post 1', 'slug' => 'post-1', 'body' => 'Post 1 body', 'published_at' => now()],
    ['name'=>'Post 2', 'slug' => 'post-2', 'body' => 'Post 2 body', 'published_at' => now()],
]);
Another way to write the code above is to separate the data into its own variable and then just reference the variable like below.
<?php

use App\Models\Post;

$posts = [
    ['name'=>'Post 1', 'slug' => 'post-1', 'body' => 'Post 1 body', 'published_at' => now()],
    ['name'=>'Post 2', 'slug' => 'post-2', 'body' => 'Post 2 body', 'published_at' => now()],
];

Post::insert($posts);
Do note that performance will be slightly slower when you insert many data at the same time.

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

)