user5638730 user5638730 - 25 days ago 24
PHP Question

Laravel - seed Data for categories

I'm currently got stuck with the following: I'm trying to implement a catgeory system to my app. Therefore, I need about 100-200 categories with some "parent categories". So I want to create two tables: Category, Subcategory. The category table holds the parent categories, the subcategories are the subcategory of those, pointing to the primary key of the parent category. Here's what I mean with the category thing:

Parent Category: Clothing

Subcategory: Woman Shoes

Subcategory: Men's Shirts

Subcategory: Jeans

Parent Category: Handys

Subcategory: Smartphones

Subcategory: PDA's

Subcategory: Smartwatches

and so on.

What I tried is this:

$categories = array(['name' => 'Clothing'], ['name' => 'Handy']);
$sub_categories = array(
'Clothing' => ['name' => ' Woman Shoes '], ['name' => 'Men\'s Shirts'],
'Handy' => ['name' => ' Smartphones '], ['name' => 'Smartwatches ']
);


foreach($categories as $category)
{
$category = Category::create($category);
foreach ($sub_categories as $sub_category)
{
$active = $sub_category[$category->name];
$active['parent_id'] = $categories->id;
SubCategory::create($active);
}
}


But I'm getting the error (when seeding)
index undefined: clothing
, guessing it's because of that part:
$sub_category[$category->name];
... But how can I do it better? Or how can I get this working?

I also tried that (in the inner foreach):

$subcategory = new Subcategory();
$subcategory->name = $sub_category['name'];
$subcategory->parent_id = $category['id'];
$subcategory->save();


This way, there are no errors, but every parent category has every subcategory, so I don't look for the subcategories parents.

How can I get what I want?

Answer

I've tested this and it works fine:

$data = [
    'Clothing' => ['Woman Shoes', 'Men\'s Shirts'],
    'Handy' => ['Smartphones', 'Smartwatches ']
];

foreach ($data as $category => $subCategories)
{
    $id = Category::create(['name' => $category])->id;

    foreach ($subCategories as $subCategory) {
        SubCategory::create([
            'parent_id' => $id,
            'name' => $subCategory
        ]);
    }
}

Don't forget to add all fields to $fillable since you're using create() method.

Comments