Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Welcome Notification Laravel Package

spatie/laravel-welcome-notification

Send welcome emails to new Laravel users with a secure, expiring link to set their initial password. Adds migrations and a trait for your User model, plus a controller you extend to show the welcome form and save the password.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-welcome-notification
    

    Publish the config file (optional):

    php artisan vendor:publish --provider="Spatie\WelcomeNotification\WelcomeNotificationServiceProvider"
    
  2. First Use Case: Trigger the welcome notification when a user registers:

    // In your registration controller or observer
    $user->sendWelcomeNotification(now()->addDay());
    

    This sends a notification with a secure password-reset link that expires after 24 hours.

  3. Where to Look First:

    • Config: config/welcome-notification.php (customize notification class, expiration logic, or email template).
    • Notification Class: app/Notifications/WelcomeNotification.php (override the default to customize content).
    • Routes: routes/web.php (ensure /welcome-notification/{token} is accessible for link redirection).

Implementation Patterns

Core Workflows

  1. Triggering the Notification:

    • Use sendWelcomeNotification($expiresAt) in registration logic (e.g., UserObserver, RegisterController).
    • Pass a Carbon instance or timestamp for expiration (default: 24 hours).
    // Example in a registration observer
    public function created(User $user)
    {
        $user->sendWelcomeNotification(now()->addHours(12));
    }
    
  2. Customizing the Notification:

    • Extend the default WelcomeNotification:
      php artisan make:notification CustomWelcomeNotification
      
      Update the config to use your class:
      'notification_class' => \App\Notifications\CustomWelcomeNotification::class,
      
    • Override toMail() or toArray() to modify content:
      public function toMail($notifiable)
      {
          return (new MailMessage)
              ->subject('Welcome to ' . config('app.name'))
              ->line('Click here to set your password:')
              ->action('Set Password', url('/welcome-notification/' . $this->token));
      }
      
  3. Handling the Secure Link:

    • The package generates a secure token via Spatie\WelcomeNotification\WelcomeNotificationToken.
    • Redirect users to /welcome-notification/{token} after clicking the link.
    • Use middleware to validate tokens (e.g., WelcomeNotificationMiddleware):
      Route::get('/welcome-notification/{token}', [WelcomeNotificationController::class, 'show'])
           ->middleware(['auth', 'welcome.notification']);
      
  4. Integration with Auth:

    • Combine with Laravel’s MustVerifyEmail trait if sending email verification:
      use Illuminate\Auth\MustVerifyEmail;
      
      class User extends Authenticatable implements MustVerifyEmail
      {
          // ...
      }
      
    • Trigger welcome notification after email verification if needed.
  5. Testing:

    • Mock the notification in tests:
      $user = User::factory()->create();
      $user->shouldReceive('sendWelcomeNotification')
           ->once()
           ->with(now()->addDay());
      

Gotchas and Tips

Pitfalls

  1. Token Expiration:

    • Tokens expire by default after 24 hours (configurable via $expiresAt).
    • Debugging: Check welcome_notification_tokens table for stale tokens if users report broken links.
    • Fix: Extend expiration in config or dynamically:
      $user->sendWelcomeNotification(now()->addWeeks(1));
      
  2. Notification Delivery:

    • If emails aren’t sending, verify:
      • Laravel’s mail config (config/mail.php).
      • Queue workers are running (php artisan queue:work).
      • The WelcomeNotification class is properly registered in config.
  3. Token Security:

    • Tokens are signed with Laravel’s hash helper by default.
    • Tip: Use config(['welcome-notification.token_cipher' => 'AES-256-CBC']) for stronger encryption if needed.
  4. Route Conflicts:

    • Ensure /welcome-notification/{token} doesn’t conflict with existing routes.
    • Tip: Use route model binding or middleware to validate tokens before processing.
  5. Database Concerns:

    • The package creates a welcome_notification_tokens table.
    • Tip: Run migrations manually if using custom database setups:
      php artisan migrate
      

Debugging Tips

  1. Log Token Generation: Add a created observer to log tokens for debugging:

    public function created(WelcomeNotificationToken $token)
    {
        \Log::debug('Welcome token created:', ['token' => $token->token]);
    }
    
  2. Check Mail Logs: Use Laravel’s mail logging to verify notifications are sent:

    'mail' => [
        'log' => env('MAIL_LOG', false),
    ],
    
  3. Override Token Logic: Customize token generation in app/Providers/WelcomeNotificationServiceProvider.php:

    public function boot()
    {
        WelcomeNotificationToken::creating(function ($token) {
            $token->custom_field = 'value';
        });
    }
    

Extension Points

  1. Custom Token Storage: Override the token model to use a different database or cache:

    class CustomWelcomeNotificationToken extends WelcomeNotificationToken
    {
        public $timestamps = false;
        protected $connection = 'mysql_custom';
    }
    

    Update the config to point to your model.

  2. Multi-Channel Notifications: Extend the notification to support SMS or push:

    public function via($notifiable)
    {
        return ['mail', 'nexmo']; // Add SMS channel
    }
    
  3. Dynamic Expiration: Use a closure for dynamic expiration logic:

    $user->sendWelcomeNotification(fn () => now()->addDays(config('welcome-notification.dynamic_days')));
    
  4. Localization: Localize the notification content:

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->subject(__('welcome.subject'))
            ->line(__('welcome.greeting', ['name' => $notifiable->name]));
    }
    
  5. Event-Based Triggers: Listen for the WelcomeNotificationSent event to add side effects:

    WelcomeNotificationSent::listen(function ($notification) {
        \Log::info("Welcome sent to {$notification->notifiable->email}");
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport