Laravel 5: How to saveMany() based on value
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
# Mastering Bulk Operations: How to Use `saveMany()` Efficiently in Laravel
As developers working with Eloquent and relational databases, we often encounter scenarios where we need to create multiple related records based on a single input value. The initial instinct, as seen in the provided example, is to loop through the data and call methods like `saveMany()` for each item. While this approach works, it often leads to unnecessary database overhead, especially when dealing with large datasets.
This post will dive into how to optimize this process, moving from iterative saving to efficient bulk operations using Laravel's Eloquent capabilities. We will explore why and how to achieve the desired result—saving multiple `ContainerSlot` records based on a dynamic count in a single, efficient operation.
## The Inefficiency of Iterative Saving
Your initial approach involved iterating over the data and calling `$platecontainer->containerSlots()->saveMany([...])` inside a loop for every iteration:
```php
foreach ($data as $key => $value) {
$platecontainer->containerSlots()->saveMany([
new ContainerSlot([
'plate_container_id' => $data['id'],
'slot' => $data['number_of_slots'],
'occuiped' => false,
])
]);
}
```
While this achieves the result, performing many individual database write operations within a loop is inefficient. Each call incurs the overhead of establishing a query and executing an INSERT statement on the database. For bulk operations, we want to minimize these round trips to maximize performance.
## The Bulk Approach: Saving Related Models in One Go
The key to optimizing this is to prepare all the data you need to save first (usually as a collection) and then attempt to persist that entire collection at once. When working with Eloquent, especially when creating related models, we leverage mass assignment and relationship methods effectively.
Instead of looping, we can calculate the required number of slots and create an array of the `ContainerSlot` models we intend to save. This allows us to handle the data preparation outside the database transaction loop.
Here is a refactored approach that addresses your requirement to save 5 records in descending order:
```php
// Assuming $data is the input array from your example
$containerId = $data['id'];
$numberOfSlots = $data['number_of_slots'];
// 1. Prepare the data for bulk insertion
$slotsToCreate = [];
for ($i = 0; $i < $numberOfSlots; $i++) {
$slotsToCreate[] = new ContainerSlot([
'plate_container_id' => $containerId,
'slot' => $numberOfSlots - $i, // Creating slots in descending order (5, 4, 3...)
'occuiped' => false,
]);
}
// 2. Perform the bulk save operation
// We use the model's saveMany method on the relationship to insert all records efficiently.
$platecontainer->containerSlots()->saveMany($slotsToCreate);
// This single call handles the insertion of all 5 records in one optimized operation.
```
### Why this is better: Database Efficiency
By preparing an array of models (`$slotsToCreate`) and passing it to `saveMany()`, you instruct Eloquent to handle the mass insertion more efficiently. Depending on your database setup, this can translate into a single bulk insert statement rather than $N$ separate calls. This principle of batch processing is fundamental in building high-performance applications, aligning with best practices taught by resources like those found at [laravelcompany.com](https://laravelcompany.com).
## Best Practices for Relational Data Management
When managing complex relationships and large data sets, remember these principles:
1. **Use Collections:** Always prepare your data as PHP collections before interacting with the database. This keeps the logic clean and prepares data efficiently.
2. **Minimize Queries:** Avoid N+1 query problems. By performing bulk operations, you drastically reduce the number of necessary database round trips.
3. **Database Indexing:** Ensure that the foreign keys linking your tables (like `plate_container_id` in the `ContainerSlot` table) are properly indexed. This is crucial for fast lookups and joins when dealing with large amounts of related data.
## Conclusion
Switching from iterative saving to bulk saving by preparing a collection of models is a fundamental optimization technique in Laravel development. While iterating works for small tasks, leveraging methods like `saveMany()` on collections allows you to write scalable, high-performance code that respects the capabilities of your underlying database. By focusing on batch operations, you ensure your application remains fast and efficient as it grows in complexity.