Create related data with Pest, Laravel and factories
Setting up the related testdata when creating Pest tests always keeps me searching for the syntax.
Therefore, here a little reminder to self with links to the appropriate info in the Laravel documentation.
// hasMany relation: User has many Posts - post.user_id is set $user = User::factory() ->has(Post::factory()->count(3)) ->create();
// belongsTo: post.user_id is set $post = Post::factory() ->for(User::factory()) ->create();
Many to Many: User belongsToMany Role =>
// belongsToMany: using the pivot table. NOTE the array as first argument! $user = User::factory() ->hasAttached([$tag], [<pivot fields>], 'roles') ->create();