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 How to Call an External Url API in Laravel

How to Call an External Url API in Laravel ?

June 5, 2022June 5, 2022

In this article we will learn to call an external Url API in Laravel. Whenever we want to access the third party data we need to access the data using the APIs, we send a request to another server means outside our application and they respond with preformatted structure. In…

Read More
Php How to create custom logs file in laravel 8 9

How to create custom logs file in laravel 8 / 9 ?

May 16, 2022May 16, 2022

In this article i will show you to use and create custom logs file in laravel. Logging is an important aspect when you want to debug your application or you want to monitor the user activities on the application. Laravel itself provides a robust library to create logging on daily…

Read More

how to add multiple select in laravel eloquent ?

December 29, 2021February 22, 2024

Laravel eloquent builder has rich features to modify the query. In some cases we wanted to add multiple select in laravel and modify the select statement on basis of few conditions and wanted to add some select statement on condition. so in this article we will learn to add multiple…

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

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • 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
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version