Member-only story

Enhancing Data Creation Efficiency with Laravel’s recycle Method

I Nyoman Jyotisa
2 min readJan 19, 2025

Laravel’s factory system introduces the powerful recycle method, enabling the reuse of existing model instances across multiple factory calls. This approach simplifies creating complex data structures with shared relationships, reducing redundancy and improving test performance.

Basic Recycling Example

Here’s how to use the recycle method for efficient data creation:

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

Practical Example: E-Commerce Testing

Below is a real-world example of leveraging the recycle method to simulate an e-commerce testing environment:

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()
{
// Step 1: Create the base structure
$store = Store::factory()->create();
$categories = Category::factory()
->count(3)
->recycle($store)
->create();
// Step 2: Add products to categories
$products =…

--

--

No responses yet