Summer Sale! All accounts are 50% off this week.

jrdavidson's avatar

Model Factories with Attaching And Associating

I'm looking for a way that I can simplify this code here from a test. I do a lot of this in many of my tests so creating this will help me. What I want to do is create two users and add attach them to a team and then associate them with the current team on that user model. The reason I have a belongsToMany and a BelongsTo relationship is due to the reason of keeping a history of teams the user has belonged to as well as knowing what the current team is.

[$userA, $userB] = User::factory()->count(2)->create();
$team = Team::factory()
    ->withCurrentUser($userA)
    ->withCurrentUser($userB)
    ->bookable()
    ->create();

$userA->currentTeam()->associate($team);
$userA->save();
$userB->currentTeam()->associate($team);
$userB->save();

TeamFactory.php

public function withCurrentUser($user, $joinDate = null)
{
    $this->hasAttached($user, ['joined_at' => $joinDate ?? now()]);

    return $this;
}
0 likes
0 replies

Please or to participate in this conversation.