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

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Generate Laravel Validation Rules From a JSON Schema image

Generate Laravel Validation Rules From a JSON Schema

Read article
Laravel Suspicious Login: Detect and Block Risky Logins image

Laravel Suspicious Login: Detect and Block Risky Logins

Read article
Decide with Jev: Make Failed AI Requests Safe in Laravel image

Decide with Jev: Make Failed AI Requests Safe in Laravel

Read article
Black Friday: Learn the habits behind AI workflows that work image

Black Friday: Learn the habits behind AI workflows that work

Read article
Laravel Black Friday and Cyber Monday Deals 2026 image

Laravel Black Friday and Cyber Monday Deals 2026

Read article
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article