t0berius
2 weeks ago
299
17
Testing

laravel factory relation

Posted 2 weeks ago by t0berius

Is there a way to create related models from arrays for a hasMany relation inside laravel model factories?

CategoryTableSeeder:

$categories = [
        'Food' => [
            'burger',
	    'pasta',
        ],
        'Drinks' => [
            'softdrinks',
            'cocktails',
        ],
    ];

    foreach ($categories as $category) {

        Category::factory()->make([
            'name'   => $category,
        ])->save();
    //make sure the subcategories with corresponding names are created too

    }

My Category model already has a relation for the subcategories:

public function subcategories()
{
    return $this->hasMany('App\SubCategory');
}

Is there a way I can create the subcategories for every model and override the name of the subcategory (using the one from the array above).

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