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 Add or Update Index in Laravel Migration

How to Add or Update Index in Laravel Migration?

August 21, 2022March 16, 2024

Add or Update Index in Laravel Migration can be implement easily using the migrations libraries index method. Migrations provides almost all feature to create the database schema and create and update index in laravel migration. As We know database index is used to improve the speed of tables. Index can…

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
Php Laravel orderBy clause in eloquent with example

Laravel orderBy clause in eloquent with example

October 5, 2022March 16, 2024

In this blog post, we will take a look at how to use the Laravel orderBy clause in the Eloquent ORM.Laravel provides an expressive, fluent interface for creating and retrieving records in your database. When we work with databases in Laravel, we often need to order the results we get…

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