Service Provider
What MagicStarterServiceProvider registers and in which order: config, contract bindings, routes, rate limiters, Sanctum and password reset customisation, event listeners, the team policy, translations and the publish tags.
On this page
Quick Reference#
| To do this | Do this |
|---|---|
| Replace a default action | $this->app->bind(Contract::class, YourAction::class) in your AppServiceProvider::register(). |
| Skip the package routes | Call MagicStarter::ignoreRoutes() in register() and define your own. |
| Move the routes | Set magic-starter.route_prefix. The social callback routes under magic-starter/social/ load outside the prefix and stay where they are. |
| Add middleware to the routes | List it in magic-starter.route_middleware. |
| Publish an asset | php artisan vendor:publish --tag=<tag>; the tags are listed under Configuration Publishing. |
Introduction#
AnilcanCakir\MagicStarter\MagicStarterServiceProvider is the single entry point for the package. It is registered automatically through Laravel's package auto-discovery mechanism (extra.laravel.providers in composer.json), so no manual registration is required in config/app.php.
The provider is responsible for merging configuration, binding every action contract to its default implementation, suppressing Sanctum's own migrations, registering rate limiters, loading routes, wiring event listeners, and publishing all publishable assets.
Bootstrap Lifecycle#
MagicStarterServiceProvider follows the standard two-phase Laravel provider lifecycle.
register()#
Runs before the application fully boots. Only IoC container work happens here:
- Merges
config/magic-starter.phpunder themagic-starterkey viamergeConfigFrom(). - Calls
Sanctum::ignoreMigrations()to prevent Sanctum from auto-loading its ownpersonal_access_tokensmigration (the package ships a custom version with additional device info columns). - Binds all action contracts to their default implementations (see Contract Bindings).
boot()#
Runs after all providers have registered. All side-effectful setup happens here, in this order:
configureRateLimiting(): registers namedRateLimiterdefinitions.- Sanctum model swap:
Sanctum::usePersonalAccessTokenModel(Models\PersonalAccessToken::class). - Password reset URL customization via
ResetPassword::createUrlUsing(). - Team policy and
Registeredevent listener registration (whenFeatures::hasTeamFeatures()). - Notification channel gating listener registration (when
Features::hasNotificationFeatures()). - Translation loading via
loadTranslationsFrom(). - Route loading via
loadRoutesFrom()(unlessMagicStarter::shouldIgnoreRoutes()). Withsocial-loginon,routes/social.phploads as well: the provider callback and Apple notification routes, outside the route prefix. - With
social-loginon: wires the Microsoft Socialite driver, and logs a warning whensocial.redirects.androidis set and is not an https App Link. - Console-only: command registration and
publishes()/publishesMigrations()calls.
Contract Bindings#
All bindings are registered in register(). Each entry maps an interface from Contracts/ to a default action in Actions/. Consuming applications override any binding with $this->app->bind(...) in their own AppServiceProvider::register().
| Contract | Default Implementation | Domain |
|---|---|---|
Contracts\CreatesUsers |
Actions\CreateUser |
Auth |
Contracts\UpdatesUserProfiles |
Actions\UpdateUserProfile |
Auth / Profile |
Contracts\UpdatesUserPasswords |
Actions\UpdateUserPassword |
Auth |
Contracts\DeletesUsers |
Actions\DeleteUser |
Auth |
Contracts\SchedulesUserDeletion |
Actions\ScheduleUserDeletion |
Account deletion |
Contracts\ReleasesUserBilling |
Actions\ReleaseUserBilling |
Account deletion |
Contracts\CreatesTeams |
Actions\CreateTeam |
Teams |
Contracts\UpdatesTeams |
Actions\UpdateTeam |
Teams |
Contracts\DeletesTeams |
Actions\SubscriptionGuardedDeleteTeam |
Teams |
Contracts\TrashesTeams |
Actions\SubscriptionGuardedTrashTeam |
Teams |
Contracts\AddsTeamMembers |
Actions\AddTeamMember |
Teams |
Contracts\RemovesTeamMembers |
Actions\RemoveTeamMember |
Teams |
Contracts\InvitesTeamMembers |
Actions\InviteTeamMember |
Teams |
Contracts\AcceptsTeamInvitations |
Actions\AcceptTeamInvitation |
Teams |
Contracts\UpdatesTeamMemberRoles |
Actions\UpdateTeamMemberRole |
Teams |
Contracts\CreatesGuestUsers |
Actions\CreateGuestUser |
Guest Auth |
Contracts\SendsOtpCodes |
Actions\LogOtpProvider |
OTP |
Contracts\VerifiesOtpCodes |
Actions\CacheOtpVerifier |
OTP |
Contracts\EnablesTwoFactorAuthentication |
Actions\EnableTwoFactorAuthentication |
2FA |
Contracts\ConfirmsTwoFactorAuthentication |
Actions\ConfirmTwoFactorAuthentication |
2FA |
Contracts\DisablesTwoFactorAuthentication |
Actions\DisableTwoFactorAuthentication |
2FA |
Contracts\GeneratesNewRecoveryCodes |
Actions\GenerateNewRecoveryCodes |
2FA |
Contracts\ResolvesSocialUsers |
Actions\ResolveSocialUser |
Social login |
Contracts\CreatesUsersFromProvider |
Actions\CreateUserFromProvider |
Social login |
Contracts\ConnectsSocialAccounts |
Actions\ConnectSocialAccount |
Social login |
Contracts\DisconnectsSocialAccounts |
Actions\DisconnectSocialAccount |
Social login |
Contracts\SetsUserPasswords |
Actions\SetUserPassword |
Social login |
In addition to the interface bindings, Support\TwoFactorAuthenticationProvider and Social\AppleProviderFactory are registered as singletons:
$this->app->singleton(Support\TwoFactorAuthenticationProvider::class);
$this->app->singleton(Social\AppleProviderFactory::class);
Example override:
// app/Providers/AppServiceProvider.php
use AnilcanCakir\MagicStarter\Contracts\CreatesUsers;
public function register(): void
{
$this->app->bind(CreatesUsers::class, \App\Actions\MagicStarter\CreateUser::class);
}
Route Registration#
Routes are loaded in boot() from src/routes/api.php:
if (! MagicStarter::shouldIgnoreRoutes()) {
$this->loadRoutesFrom(__DIR__ . '/routes/api.php');
}
Call MagicStarter::ignoreRoutes() in your AppServiceProvider::register() to skip route loading entirely and define your own routes manually.
The route prefix is read from config('magic-starter.route_prefix') (default: api/v1) and applied globally to all package routes. Every route group is additionally gated by its corresponding feature flag: routes for disabled features are never registered.
Rate Limiters#
configureRateLimiting() registers named RateLimiter definitions. The ones below are keyed by a combination of IP address and a request-specific discriminator to prevent credential-stuffing while not unfairly blocking shared NATs. An IPv6 address is collapsed to its /64 before it becomes part of a key (an IPv4 address is used as is), because one subscriber is routinely handed a whole /64 and a key on the full address would give that host a fresh bucket per address.
| Limiter Name | Limit | Key Strategy |
|---|---|---|
magic-starter-auth-login |
5 / minute | ip|email |
magic-starter-auth-register |
3 / minute | ip |
magic-starter-auth-social |
10 / minute | ip|provider |
magic-starter-auth-password-reset |
3 / minute | ip|email |
magic-starter-2fa-challenge |
5 / minute | ip|two_factor_token |
magic-starter-guest-auth |
10 / minute | ip|device_id |
magic-starter-otp (send) |
2 / minute | ip|send|phone |
magic-starter-otp (verify) |
5 / minute | ip|verify|phone |
magic-starter-settings |
30 / minute | ip |
magic-starter-email-verification |
1 / minute | user.id or ip |
magic-starter-auth-handoff |
10 / minute | user.id|ip |
magic-starter-auth-handoff-exchange |
10 / minute | ip |
magic-starter-releases |
60 / minute | ip |
magic-starter-push-test |
5 / minute | user.id or ip |
The support routes carry their own limiters, described with the support desk.
The magic-starter-otp limiter is a single named limiter that branches internally on whether the request path contains otp/send.
The magic-starter-auth-social limiter covers every social route: the redirect, the exchange, the native token endpoint, the provider callback, and the authenticated link ticket, disconnect and set-password routes. The provider half of the key is the {provider} route segment, so it is empty on the routes that carry none, and those share one bucket per IP. See Social Login.
Sanctum Customization#
The package performs two distinct Sanctum customizations.
Migration Suppression (register())#
if (class_exists(Sanctum::class) && method_exists(Sanctum::class, 'ignoreMigrations')) {
Sanctum::ignoreMigrations();
}
This prevents Sanctum from publishing or running its own personal_access_tokens migration, because the package ships its own version plus an additive migration (add_device_info_to_personal_access_tokens_table) that adds:
ip_address:string(45), nullable, stores the client's IPv4 or IPv6 address.user_agent:text, nullable, stores the rawUser-Agentheader.
Model Swap (boot())#
Sanctum::usePersonalAccessTokenModel(Models\PersonalAccessToken::class);
Models\PersonalAccessToken extends Laravel\Sanctum\PersonalAccessToken and applies ConditionallyUsesUuids so that token IDs respect the application's UUID/integer PK configuration.
Password Reset URL#
The package customizes the password reset notification URL in boot() so that it points at the frontend application rather than the backend:
ResetPassword::createUrlUsing(function (object $notifiable, string $token) {
$frontendUrl = FrontendUrl::baseOrNull() ?? rtrim(url('/'), '/');
return "{$frontendUrl}/auth/reset-password?token={$token}&email="
. $notifiable->getEmailForPasswordReset();
});
The URL is constructed as:
{frontend_url}/auth/reset-password?token={token}&email={email}
Config resolution falls back from magic-starter.frontend_url → app.frontend_url, so either key works, and the URL is absolute in every configuration: with neither key usable it falls back to the application root rather than emitting a host-less /auth/reset-password?token=... that no mail client can resolve.
Support\FrontendUrl::baseOrNull() is the shared predicate behind all three link builders (this one, TeamInvitationNotification, VerifyEmailNotification). It answers null for four inputs, not one: a missing key, an empty string, a whitespace-only value, and a slash-only value.
Event Listeners#
The provider registers two event listeners, each guarded by a feature flag check.
Personal Team Creation#
Condition: Features::hasTeamFeatures() returns true.
Event::listen(Registered::class, Listeners\CreatePersonalTeamListener::class);
CreatePersonalTeamListener handles Illuminate\Auth\Events\Registered. When a new user registers, the listener:
- Performs an idempotency check via a direct DB query (not a cached relationship) to prevent duplicate teams from race conditions or repeated event dispatches.
- Creates a personal team named using the user's first name and locale (via
magic-starter::teams.personal_team_nametranslation key). - Attaches the user to the new team's membership pivot with
Role::OWNER. - Clears the
ownedTeamsandteamscached relations on the user. - Sets
current_team_idon the user to the new team's ID.
Notification Channel Gating#
Condition: Features::hasNotificationFeatures() returns true.
Event::listen(NotificationSending::class, Listeners\GateNotificationChannels::class);
GateNotificationChannels handles Illuminate\Notifications\Events\NotificationSending (fired per-channel, per-notifiable before delivery). The listener:
- Resolves the notification class FQCN from the event.
- Returns
true(allow) if the notification class is not registered inNotificationPreferenceRegistry. - Returns
trueif the notifiable does not implementprefers(). - Returns
truefor unknown or locked channels. 4a. Returnstruewhen the notification implementsBypassesNotificationPreferencesandbypassesPreference($notifiable, $logicalChannel)says so. - Calls
$notifiable->prefers($slug, $logicalChannel)as the final gate; returningfalsecancels delivery for that channel.
Team Policy#
When Features::hasTeamFeatures() is true, the provider auto-registers Policies\TeamPolicy for the resolved team model:
Gate::policy(MagicStarter::teamModel(), Policies\TeamPolicy::class);
MagicStarter::teamModel() resolves dynamically: it checks config('magic-starter.models.team') first, then falls back to App\Models\Team via class_exists(). This ensures the policy is registered against whatever model class the consuming application is using.
Translation Loading#
$this->loadTranslationsFrom(__DIR__ . '/../lang', 'magic-starter');
Translation files are loaded under the magic-starter namespace. All package-owned translatable strings (e.g., team name templates, validation messages) use this namespace prefix, for example magic-starter::teams.personal_team_name.
To override translations, publish them with:
php artisan vendor:publish --tag=magic-starter-lang
Published files land in lang/vendor/magic-starter/.
Configuration Publishing#
All publish registrations are wrapped in if ($this->app->runningInConsole()) to avoid overhead during normal request handling. The following tags are registered:
| Tag | Source | Destination |
|---|---|---|
magic-starter-config |
config/magic-starter.php |
config/magic-starter.php |
magic-starter-migrations |
database/migrations/ |
database/migrations/ |
magic-starter-stubs |
stubs/actions/ |
app/Actions/MagicStarter/ |
magic-starter-policies |
stubs/policies/ |
app/Policies/ |
magic-starter-models |
stubs/models/Team.php, TeamUser.php, TeamInvitation.php |
app/Models/ |
magic-starter-lang |
lang/ |
lang/vendor/magic-starter/ |
magic-starter-user-model |
stubs/models/User.php |
app/Models/User.php |
magic-starter-factories |
stubs/factories/UserFactory.php |
database/factories/UserFactory.php |
Migrations are registered via publishesMigrations() (introduced in Laravel 11) rather than publishes(), which enables the --ansi timestamping behaviour and migration status tracking.
Install Command#
$this->commands([InstallCommand::class]);
Console\InstallCommand is registered only when running in the console. The command (magic-starter:install) provides an interactive setup wizard (Laravel Prompts) and a non-interactive flag-driven mode for CI pipelines. It publishes config, selectively publishes feature-relevant migrations, optionally publishes team model stubs, and can immediately run php artisan migrate.
See the Installation guide for full usage documentation including all available --flags.
Related Documentation#
- Action Contracts: what each bound contract does and how to override it.
- Installation: the install command and the publish tags in use.
- Configuration:
route_prefix,route_middlewareand the feature flags that gate the routes. - Models: how the model classes the provider hands to Sanctum and the policy are resolved.