has($organization, 'invitations:create')) { throw new AuthorizationException(); } $this->validate($organization, $email, $role); InvitingTeamMember::dispatch($organization, $email, $role); /** @var OrganizationInvitation $invitation */ $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))->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'); }))->withMessage(__('This user has already been invited to the team.')), ], 'role' => [ 'required', 'string', Rule::in([ Role::Owner->value, Role::Admin->value, Role::Manager->value, Role::Employee->value, ]), ], ]); } /** * 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->hasRealUserWithEmail($email), 'email', __('This user already belongs to the team.') ); }; } }