3

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.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • 1
    You can use `$user->switchTeam($team);` [source](https://github.com/laravel/jetstream/blob/1.x/src/HasTeams.php#L38) – Clément Baconnier Oct 29 '20 at 11:16
  • 1
    Thankyou! If you make this an answer, I'll be sure to mark it. I take it that this new Laravel 8.x Jetstream feature replacing Auth is new and still in a lot of beta stage within documentation @ClémentBaconnier – Jaquarh Oct 29 '20 at 11:19

1 Answers1

8

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

 $user->switchTeam($teamToAssign);
Clément Baconnier
  • 5,718
  • 5
  • 29
  • 55