Laravel model bulk insert fillablel

laravel model bulkinsert fillablel

Handling large amounts of data efficiently is essential for any Laravel application that aims to scale and perform smoothly. When it comes to inserting data, Laravel Model Bulk Insert Fillable operations can be a game-changer, drastically reducing execution time and minimizing the number of database interactions.

In this post, we’ll explore how to handle bulk inserts using Eloquent models in Laravel, focusing on the role of $fillable properties to ensure data security and avoid mass-assignment vulnerabilities.

Table of Contents

What is Bulk Insert and Why Use It?

A bulk insert is a process of adding multiple records to the database in a single query. This technique is faster and more efficient compared to individual insert operations, making it ideal for scenarios like importing large datasets or handling multiple data entries simultaneously.

Using bulk inserts has some distinct advantages:

  • Speed: By sending one query to insert all records, bulk inserts cut down the time spent on database interactions.
  • Efficiency: Fewer queries mean less load on the database, leading to better application performance.
  • Scalability: Bulk inserts can handle large data volumes better, making them a go-to for data-heavy applications.

 

But it’s not always the right choice. For instance, if you’re working with a small dataset or need individual processing per record, the standard insert method may be more appropriate.

Let's learn about Laravel Models and Fillable Properties

Laravel models are responsible for interacting with the database tables. Each model represents a table, with each instance of the model corresponding to a row in the table. Laravel uses Eloquent ORM (Object-Relational Mapping), which makes it easy to handle database operations in a structured way.

Fillable Properties

When working with models, Laravel provides a $fillable property to define which attributes are mass-assignable. Mass assignment is when multiple fields are assigned at once, like using create() or update() with an array of data. Here is an example

				
					class User extends Model
{
    protected $fillable = ['name', 'email', 'password'];
}

				
			

By specifying $fillable, we prevent mass-assignment vulnerabilities where unintended fields might be updated if the input is not properly sanitized. Only attributes listed in $fillable will be assignable when using mass assignment.

Using Laravel Model Bulk Insert with Fillable

Standard Insert vs. Bulk Insert

In Laravel, we can insert data into the database using two primary approaches:

  • Standard Insert: Using create() or save() methods for individual records.
  • Bulk Insert: Using the insert() method for multiple records in a single query.

Single Insert Example

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

				
			

Bulk Insert Example

				
					DB::table('users')->insert([
    ['name' => 'Alice', 'email' => 'alice@example.com'],
    ['name' => 'Bob', 'email' => 'bob@example.com']
]);

				
			

Using Eloquent Models for Bulk Insert with Fillable

Eloquent’s insert() doesn’t automatically validate against $fillable. However, there are ways to ensure only fillable attributes are used in a bulk insert.

Manually Filter Data by Fillable Attributes

Before inserting, we can filter each record to only include fields defined in $fillable.

Example

				
					$data = [
    ['name' => 'Alice', 'email' => 'alice@example.com', 'role' => 'admin'],
    ['name' => 'Bob', 'email' => 'bob@example.com', 'role' => 'user']
];

// Filter each record based on fillable attributes
$fillableData = array_map(function ($item) {
    return array_intersect_key($item, array_flip((new User)->getFillable()));
}, $data);

// Bulk insert
DB::table('users')->insert($fillableData);

				
			

Using Custom Bulk Insert Method with Eloquent

Create a custom method in the model to bulk insert data while respecting $fillable.

Example

				
					class User extends Model
{
    protected $fillable = ['name', 'email'];

    public static function bulkInsert(array $data)
    {
        $fillable = (new self())->getFillable();
        $filteredData = array_map(fn($item) => array_intersect_key($item, array_flip($fillable)), $data);

        DB::table((new self())->getTable())->insert($filteredData);
    }
}

// Usage
User::bulkInsert([
    ['name' => 'Charlie', 'email' => 'charlie@example.com'],
    ['name' => 'Diana', 'email' => 'diana@example.com']
]);

				
			

Optimizing Bulk Inserts for Large Data Sets

For very large data sets, bulk inserts can be optimized further to prevent memory issues and enhance performance.

Chunked Inserts

Chunking allows us to break down large datasets into smaller pieces, which are then inserted in batches. This helps in managing memory and reducing the load on the database.

Example

				
					$users = [
    // Large dataset here
];

foreach (array_chunk($users, 1000) as $chunk) {
    DB::table('users')->insert($chunk);
}

				
			

Using Transactions for Safe Bulk Inserts

Wrapping bulk inserts within a transaction ensures that all records are inserted successfully, or none at all if an error occurs.

Example

				
					DB::transaction(function () use ($users) {
    DB::table('users')->insert($users);
});
				
			

Handling Duplicates with upsert()

In cases where you might face duplicate entries, Laravel’s upsert() method, introduced in Laravel 8, can help. It allows you to insert records while updating existing ones based on a unique identifier.

Example

				
					$users = [
    ['email' => 'alice@example.com', 'name' => 'Alice Updated'],
    ['email' => 'bob@example.com', 'name' => 'Bob Updated']
];

User::upsert($users, ['email'], ['name']);

				
			

Here, if a record with the same email exists, the name field will be updated instead of creating a duplicate entry.

Troubleshooting Common Bulk Insert Issues

1. Mass Assignment Errors

Ensure you’ve set the $fillable property correctly for each model. If you’re encountering MassAssignmentException, check if you’ve whitelisted the correct fields in $fillable.

2. Memory Limits

If you’re hitting memory limits, try chunking your inserts, increasing memory limits in php.ini, or consider using command-line scripts for very large data sets.

3. Performance Insights Using Query Log

Laravel’s query log can provide insights into your bulk insert performance. Use DB::enableQueryLog() before the query and DB::getQueryLog() afterward to see query details.

Final Thoughts: Laravel model bulkinsert fillable

Bulk inserts in Laravel, when combined with $fillable attributes, offer a powerful and secure way to handle large-scale data operations. From performance optimization to protecting against mass-assignment vulnerabilities, mastering these techniques allows you to manage data effectively.

Experiment with the methods that best suit your project’s needs, and remember to balance security with performance in all your data-handling operations.

Written By,

Picture of Md Monayem Islam

Md Monayem Islam

Hey, I'm Md Monayem Islam. I’m a Full Stack Developer with extensive expertise in Laravel (PHP), Vue.js (TypeScript), and API development. Over the years, I’ve honed my skills in building dynamic and scalable web applications. Previously, I worked on a variety of projects, creating robust solutions and enhancing the user experience for clients worldwide. Now, I’m here to share my knowledge and help you develop web applications.

Want a FREE Consultation?

I am here to assist with your queries. Schedule now!
Share the Post:

Let's Connect!

Have a question? Contact me and I’ll get back to you soon.

Do you Need a developer for your project?