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 relations: User hasMany Post

// hasMany relation: User has many Posts - post.user_id is set
$user = User::factory()
  ->has(Post::factory()->count(3))
  ->create();

BelongsTo relations (inverse of the hasMany): Post belongsTo User => for()

// belongsTo: post.user_id is set
$post = Post::factory()
  ->for(User::factory())
  ->create();

Many to Many: User belongsToMany Role => has() and hasAttached()

// belongsToMany: using the pivot table. NOTE the array as first argument!
$user = User::factory()
  ->hasAttached([$tag], [<pivot fields>], 'roles')
  ->create();

Click Here to Leave a Comment Below

Leave a Reply: