phplaravellaravel-jetstream

How to set a users current team in Laravel Jetstream


My application requires the ability of administrators to create registration access to users. This means that the account is 'half created' for them. In this process, the team assignment is set. A link will be generated at the end of this process to allow the user to complete the account registration.

$user = App\Models\User::create(array(
    'name' => 'New Person',
    'email' => 'mail@example.com',
    'password' => Hash::make(hex2bin(random_bytes(32)),
    'callsign' => 'New C/S',
    'team'     => 1,
    'company' => 'Their company'
));

$teamToAssign = App\Models\Team::find(1); // This gets passed in but for demonstration purposes, assume its the first team
$teamToAssign->users()->attach($user, array('role' => 'participant'));
Laravel\Jetstream\Events\TeamMemberAdded::dispatch($teamToAssign, $user);

The above account creation works fine, however, Jetstream requires a "Personal Team" which can be ignored if the user has a "Current Team". I cannot find the usage in the documentation for Jetstreams to set the users current team.

I have tried:

$user->currentTeam = $teamToAssign;
$user->update();

But this does not work. I know I could use a direct database query to update the current team but would prefer the Eloquent method. How can I assign my team to the users currentTeam ? The Documentation only mentions how to see the users current team.


Solution

  • You can use the built-in method switchTeam($team) that you can find in the trait HasTeams#L38

     $user->switchTeam($teamToAssign);