Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 1, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 1, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 1, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 1, 2025

      7 MagSafe accessories that I recommend every iPhone user should have

      June 1, 2025

      I replaced my Kindle with an iPad Mini as my ebook reader – 8 reasons why I don’t regret it

      June 1, 2025

      Windows 11 version 25H2: Everything you need to know about Microsoft’s next OS release

      May 31, 2025

      Elden Ring Nightreign already has a duos Seamless Co-op mod from the creator of the beloved original, and it’ll be “expanded on in the future”

      May 31, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Student Record Android App using SQLite

      June 1, 2025
      Recent

      Student Record Android App using SQLite

      June 1, 2025

      When Array uses less memory than Uint8Array (in V8)

      June 1, 2025

      Laravel 12 Starter Kits: Definite Guide Which to Choose

      June 1, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Photobooth is photobooth software for the Raspberry Pi and PC

      June 1, 2025
      Recent

      Photobooth is photobooth software for the Raspberry Pi and PC

      June 1, 2025

      Le notizie minori del mondo GNU/Linux e dintorni della settimana nr 22/2025

      June 1, 2025

      Rilasciata PorteuX 2.1: Novità e Approfondimenti sulla Distribuzione GNU/Linux Portatile Basata su Slackware

      June 1, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Optimizing Factory Data Creation with Laravel’s recycle Method

    Optimizing Factory Data Creation with Laravel’s recycle Method

    January 2, 2025

    Optimizing Factory Data Creation with Laravel's recycle Method

    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 AppModelsStore;
    use AppModelsProduct;
    use AppModelsCategory;
    use AppModelsOrder;
    use TestsTestCase;
    
    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.


    The post Optimizing Factory Data Creation with Laravel’s recycle Method appeared first on Laravel News.

    Join the Laravel Newsletter to get all the latest
    Laravel articles like this directly in your inbox.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleError’d: Infallabella
    Next Article Microsoft Teams Notifications Package

    Related Posts

    Artificial Intelligence

    Markus Buehler receives 2025 Washington Award

    June 1, 2025
    Artificial Intelligence

    LWiAI Podcast #201 – GPT 4.5, Sonnet 3.7, Grok 3, Phi 4

    June 1, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    How TUI uses Amazon Bedrock to scale content creation and enhance hotel descriptions in under 10 seconds

    Development

    Hackers phish for data with fake Apple Watch giveaway

    Development

    Life in 3280: Inside the Dome Cities, Cyborg Aristocracy & the Galactic Peace We Never Imagined

    Artificial Intelligence

    Selenium IE Webdriver showing “Only Local connection are allowed” in TestNG

    Development

    Highlights

    News & Updates

    The Marvel Rivals team just got hit with layoffs despite its massive success

    February 19, 2025

    Marvel Rivals developers are being laid off, despite the free-to-play title’s tremendous success since launching…

    GenCast predicts weather and the risks of extreme conditions with state-of-the-art accuracy

    May 29, 2025

    CodeSOD: How to Validate an IP Address

    July 24, 2024

    I went hands-on with dozens of indie games at Gamescom Latam last week — You need to wishlist these 7 titles right now

    May 8, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.