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

Javascript Laravel Ajax Autocomplete Using Select2

Laravel Customized Autocomplete Options Using Select2

July 18, 2022July 18, 2022

In this article we will learn to use Laravel Customized Autocomplete Options Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. Autocomplete search is mostly work of javascript and…

Read More
Php How to Show Success and Error Flash Message in Laravel

How to Show Success and Error Flash Message in Laravel 10 ?

March 26, 2023March 16, 2024

This article aims to teach how to display flash messages indicating success or error in Laravel 10. Flash messages come in handy when notifying users of recent activities such as form submissions or website actions. In such cases, multiple types of messages may be required. Sometimes, error messages need to…

Read More
Php Laravel 8 ajax form validation

Laravel 8 Ajax form validation with example

October 20, 2021November 16, 2021

In this article, I will demonstrate to show Laravel server side validation using Ajax. We will use jQuery to show the validation and submit the form. Using the jQuery and AJAX we will prevent the page reloading and show the validation. In this article, we will use the same simple…

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

  • 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

  • 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
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version