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

Laravel folder paths using helpers in laravel

How to get folder paths using helpers in laravel?

August 27, 2021February 22, 2024

Laravel has helpers to get folder paths using helpers in laravel and by which we can easily get root folder, public folder, assets folder, storage folder, app folder etc. Laravel has helpers to get the path of root folder, public folder, assets folder, storage folder, app folder. To get the…

Read More
Php How to access and setup storage files after upload in laravel

How to access and setup storage files after upload in laravel ?

May 23, 2022May 26, 2022

In this article i will show you to access and setup uploaded storage files in laravel. This is strongly recommended that not to use direct URL from storage, laravel internally handle it by creating Symblink but some developers access the files of storage directly without knowing the consequences of website…

Read More
Php Multiple Ways to Apply Unique Validation with Soft Delete in Laravel

Multiple Ways to Apply Unique Validation with Soft Delete in Laravel

June 17, 2022June 17, 2022

In this article we will solve the problem of Unique Validation with Soft Delete in Laravel. Soft delete trait in laravel by default add the delete_at null query to all queries but in validation rules of unique it doesn’t apply because validation rule does not use Laravel eloquent model and…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version