Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
insert multiple rows in laravel

How to insert multiple rows in laravel ?

Aman Jain, November 12, 2023March 16, 2024

Laravel supports both types of insert statement like single and multiple. In this article we will learn to insert multiple rows in laravel. Laravel, a powerful PHP framework, provides developers with a range of functionalities to streamline database operations. One common task developers often encounter is the need to insert multiple rows into a database table efficiently. In this guide, we’ll explore various methods and best practices on how to insert multiple rows in Laravel.

Understanding the Basics

Before delving into the techniques, let’s establish a foundational understanding of the Laravel Eloquent ORM (Object-Relational Mapping) and its role in database operations. Eloquent simplifies the interaction with databases by representing database tables as classes and table rows as instances of those classes.

Leveraging Eloquent for Single Row Insertion

While inserting a single row is straightforward using Eloquent, adding multiple rows requires a different approach. The traditional create method is designed for a single record and doesn’t scale well when dealing with bulk data.

// Inserting a single row
$user = User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => bcrypt('password'),
]);

//or 

$user = new User ;
$user->name = 'John';
$user->email = "john@yopmail.com";
$user->save();

Insert multiple rows in laravel with Insert Method

When it comes to inserting multiple rows efficiently, Laravel offers the insert method. This method allows developers to insert an array of data into the database in a single query, significantly improving performance.

// Inserting multiple rows
$usersData = [
    ['name' => 'Jane Doe', 'email' => 'jane@example.com', 'password' => bcrypt('password')],
    ['name' => 'Bob Smith', 'email' => 'bob@example.com', 'password' => bcrypt('password')],
    // Add more rows as needed
];

DB::table('users')->insert($usersData);

//Or using model

User::insert($usersData);

Batch Insertion with Chunking

While the insert method is suitable for relatively small datasets, handling large datasets efficiently requires a more sophisticated approach. Laravel’s chunk method provides a solution by breaking down the dataset into smaller chunks, thus preventing memory issues.

// Batch insertion with chunking
$chunkSize = 200; // Adjust according to your needs

collect($usersData)->chunk($chunkSize)->each(function ($chunk) {
    DB::table('users')->insert($chunk->toArray());
});

Utilizing Eloquent’s CreateMany Method

Eloquent provides the createMany method, a convenient way to insert multiple rows using a single query. This method simplifies the process by accepting an array of associative arrays, each representing a record.

// Using createMany for multiple row insertion
User::createMany($usersData);

Dealing with Mass Assignment

When working with Eloquent, it’s essential to consider mass assignment protection. Laravel protects against unintended mass assignment by allowing developers to specify which model attributes are mass assignable.

// Specify mass assignable attributes in the User model
protected $fillable = ['name', 'email', 'password'];

Conclusion

In conclusion, inserting multiple rows in Laravel can be achieved through various methods, each tailored to different scenarios. Whether you opt for the straightforward insert method, the chunking approach for large datasets, or the concise createMany method, understanding these techniques empowers you to make informed decisions based on your specific use case.

Next time you find yourself needing to bulk insert data into a Laravel database, consider these methods and choose the one that best suits your requirements. Happy coding!

Related

Laravel bulk insertlaravelmultiple row

Post navigation

Previous post
Next post

Related Posts

Php Laravel custom login and register

Laravel 8 Custom login and registration with example

December 3, 2021December 3, 2021

In Laravel 8 there is multiple ways to implement the login and registration like Laravel provides its own auth with packages Jetstream, passport,sanctum, breeze and fortify. These all packages are easy to install and configure but sometimes our application requirement and design patterns are different or we can say we…

Read More
Php Target class controller does not exist in Laravel

Target class controller does not exist in laravel 8 or Laravel 9

August 20, 2022March 16, 2024

Target class controller does not exist in laravel 8 or laravel 9 error encounters in laravel versions above 8 because Before laravel 8 we can call controller without full namespace but after laravel 8, laravel team has changed the way to call the controller class. In laravel 5 and 6…

Read More
Javascript Laravel Dynamic Autocomplete Using Typehead JS

Laravel Dynamic Autocomplete Using Typehead JS

July 16, 2022July 16, 2022

In this article we will learn to use Laravel Dynamic Autocomplete Using Typehead JS. Typehead JS is useful when we want live search of bulk data. Autocomplete search is mostly work of javascript and when we want to fetch live data from database then we require the intervention of laravel…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version