Laravel Tutorials

Optimizing Factory Data Creation with Laravel's recycle Method

Published
Optimizing Factory Data Creation with Laravel's recycle Method image

Laravel's factory system introduces the recycle method, allowing efficient reuse of model instances across multiple factory calls. This feature is particularly valuable when creating complex data structures with shared relationships.

// Basic recycling
$category = Category::factory()->create();
$products = Product::factory()
    ->count(3)
    ->recycle($category)
    ->create();

Let's explore a practical example of an e-commerce testing environment:

<?php
	
namespace Tests;

use App\Models\Store;
use App\Models\Product;
use App\Models\Category;
use App\Models\Order;
use Tests\TestCase;

class StoreTest extends TestCase
{
    public function test_can_generate_sales_report()
    {
        // Create base structure
        $store = Store::factory()->create();
        $categories = Category::factory()
            ->count(3)
            ->recycle($store)
            ->create();
            
        // Create products in categories
        $products = Product::factory()
            ->count(20)
            ->recycle($store)
            ->recycle($categories)
            ->create();
            
        // Generate orders using same products
        $orders = Order::factory()
            ->count(50)
            ->recycle($store)
            ->recycle($products)
            ->create()
            ->each(function ($order) use ($products) {
                // Add 1-5 random products to each order
                $orderProducts = $products->random(rand(1, 5));
                $order->products()->attach(
                    $orderProducts->pluck('id')->mapWithKeys(function ($id) {
                        return [$id => ['quantity' => rand(1, 5)]];
                    })
                );
            });
        // Test report generation
        $report = $store->generateSalesReport();
        
        $this->assertNotNull($report);
        $this->assertEquals(50, $report->total_orders);
    }
}

The recycle method significantly improves factory performance by reusing existing models instead of creating new instances for each relationship.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article