authorize('addTeamMember', $organization); $this->validate($organization, $email, $role); InvitingTeamMember::dispatch($organization, $email, $role); $invitation = $organization->teamInvitations()->create([ 'email' => $email, 'role' => $role, ]); Mail::to($email)->send(new TeamInvitation($invitation)); } /** * Validate the invite member operation. */ protected function validate(Organization $organization, string $email, ?string $role): void { Validator::make([ 'email' => $email, 'role' => $role, ], $this->rules($organization), [ 'email.unique' => __('This user has already been invited to the team.'), ])->after( $this->ensureUserIsNotAlreadyOnTeam($organization, $email) )->validateWithBag('addTeamMember'); } /** * Get the validation rules for inviting a team member. * * @return array> */ protected function rules(Organization $organization): array { return array_filter([ 'email' => [ 'required', 'email', new UniqueEloquent(OrganizationInvitation::class, 'email', function (Builder $builder) use ($organization) { /** @var Builder $builder */ return $builder->whereBelongsTo($organization, 'organization'); }), ], 'role' => Jetstream::hasRoles() ? ['required', 'string', new Role] : null, ]); } /** * Ensure that the user is not already on the team. */ protected function ensureUserIsNotAlreadyOnTeam(Organization $organization, string $email): Closure { return function ($validator) use ($organization, $email) { $validator->errors()->addIf( $organization->hasUserWithEmail($email), 'email', __('This user already belongs to the team.') ); }; } }