Home / Snippets / How to Bulk Insert Using Eloquent ORM In Laravel
How to Bulk Insert Using Eloquent ORM In Laravel cover

How to Bulk Insert Using Eloquent ORM In Laravel

10.6K

2 years ago

0 comments

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.
notion avatar

Ahabz

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

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this