p0t4t0
1 year ago

how to iterate through associative array in factory seeders?

Posted 1 year ago by p0t4t0

I have the code below in my CategoriesTableSeeder

$filters = [
          'Accessories' => [
            'Type' => ['First Aid Kits', 'Tent Poles & Stakes', 'Stuff Sacks'],
          ],
          'Backpacks' => [
            'Size' => ['27L', '32L', '40L', '44L', '50L', '55L', '60L', 'More'],
          ],
          'Cooking Gear' => [
            'Type' => ['Titanium', 'Teflon (Non-Stick)'],
          ],
          'Tents' => [
            'Size' => ['1-Person', '2-Person', '3-Person', '4-Person'],
            'Type' => ['1 Season', '2 Season', '3 Season', '4 Season'],
          ],
          'Hydration bladders' => [
            'Size' => ['0.75L', '1.0L', '1.5L', '1.8L', '2.0L', '3.0L', '4L', 'More'],
          ],
          'Lighting' => [
            'Type' => ['LED', 'Rechargeable'],
          ],
          'Men\'s Clothing' => [
            'Size' => ['XXXS', 'XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'],
            'Type' => ['Shirts', 'Pants', 'Shorts', 'Jackets', 'Shoes', 'Underwear'],
            'Material' => ['Fleece', 'Gore-Tex', 'Synthetic'],
          ],
          'Sleeping Bags' => [
            'Type' => ['1 Season', '2 Season', '3 Season', '4 Season'],
          ],
          'Sleeping Pads' => [
            'Type' => ['Air', 'Foam', 'Self-Inflating'],
          ],
          'Trekking Poles' => [
            'Type' => ['Folding', 'Telescoping'],
          ],
          'Water Bottles' => [
            'Size' => ['1.0L', '1.5L', '2.0L', '3.0L'],
          ],
          'Women\'s Clothing' => [
            'Size' => ['XXXS', 'XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'],
            'Type' => ['Shirts', 'Pants', 'Shorts', 'Jackets', 'Shoes', 'Underwear'],
            'Material' => ['Fleece', 'Gore-Tex', 'Synthetic'],
          ],
        ];

        factory(App\Category::class, 12)->create()->each(function($c) use ($filters) {
          $c->filters()->saveMany( factory(App\SearchFilter::class, foreach($filters[$c->name] as $key => $item) {
            return sizeof($item);
          })->make([
            'name' => $filters[$c->name][$key][$item],
            'filter' => $filters[$c->name][$key]
          ]) );
        });

I've been staring at it for hours and I just can't seem to figure it out, how am I supposed to pass a dynamic second argument to the factory() method which should be the total number of values in each key (Size, Type and/or Material) as well as passing it to the make method to let my FilterFactory know that name should be this and the filter should be that? I just don't get it.

here is my FilterFactory.php file btw

<?php

$factory->define(App\Filter::class, function () {
    return [
        'category_id' => null,
        'name' => null,
        'filter' => null,
    ];
});

Please sign in or create an account to participate in this conversation.