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 Beacon Laravel Package

rohitshakya/laravel-beacon

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Notification

  1. Install & Publish Config

    composer require rohitshakya/laravel-beacon
    php artisan vendor:publish --tag=beacon-config
    
    • Review config/beacon.php for default settings (e.g., notifiable_model, channels, views).
  2. Add Notifiable Trait Extend your model (e.g., User, Reseller) with Laravel’s Notifiable trait:

    use Illuminate\Notifications\Notifiable;
    
    class User extends Authenticatable
    {
        use Notifiable; // Required for Beacon
    }
    
  3. Trigger a Test Notification

    use App\Notifications\TestNotification;
    
    // In a controller or command
    auth()->user()->notify(new TestNotification());
    
    • Verify the notification appears in the topbar dropdown and inbox page (/notifications).
  4. Livewire Integration (Optional) Add the Livewire component to your layout (e.g., resources/views/layouts/app.blade.php):

    @livewire('beacon::topbar')
    

First Use Case: User Alerts

  • Scenario: Notify users when their profile is updated.
  • Implementation:
    1. Create a notification class:
      namespace App\Notifications;
      use Illuminate\Notifications\Notification;
      use rohitshakya\Beacon\Messages\BeaconMessage;
      
      class ProfileUpdated extends Notification
      {
          public function via($notifiable)
          {
              return ['database', 'beacon']; // Add 'beacon' to use Beacon
          }
      
          public function toBeacon($notifiable)
          {
              return (new BeaconMessage)
                  ->title('Profile Updated')
                  ->body('Your profile has been successfully updated.')
                  ->icon('fas fa-user-edit');
          }
      }
      
    2. Dispatch the notification in your controller:
      auth()->user()->notify(new ProfileUpdated());
      

Implementation Patterns

Core Workflows

  1. Multi-Notifiable Models

    • Bind Beacon to multiple models (e.g., User, Reseller) by configuring notifiable_models in beacon.php:
      'notifiable_models' => [
          \App\Models\User::class,
          \App\Models\Reseller::class,
      ],
      
    • Use beacon()->forModel($model) in Livewire components to target specific channels.
  2. Realtime Updates with Echo/Reverb

    • Configure broadcasting in beacon.php:
      'broadcasting' => [
          'driver' => 'pusher',
          'key' => env('PUSHER_APP_KEY'),
          'secret' => env('PUSHER_APP_SECRET'),
          'app_id' => env('PUSHER_APP_ID'),
          'options' => ['cluster' => env('PUSHER_APP_CLUSTER')],
      ],
      
    • Listen for events in your frontend:
      Echo.channel(`beacon.${userId}`)
          .listen('BeaconEvent', (data) => {
              console.log('New notification:', data);
          });
      
  3. Customizing Views

    • Publish and override default views:
      php artisan vendor:publish --tag=beacon-views
      
    • Modify resources/views/vendor/beacon/topbar.blade.php or inbox.blade.php to match your app’s design.
  4. Multiple Topbars on a Page

    • Use the beacon helper to generate unique components:
      @livewire('beacon::topbar', ['model' => \App\Models\Reseller::class])
      
    • Bind each to a private channel in beacon.php:
      'channels' => [
          'users' => 'beacon.users',
          'resellers' => 'beacon.resellers',
      ],
      

Integration Tips

  • Livewire Components

    • Extend Beacon’s Livewire components for custom logic:
      use rohitshakya\Beacon\Http\Livewire\Topbar;
      
      class CustomTopbar extends Topbar
      {
          public function mount()
          {
              parent::mount();
              // Add custom logic (e.g., filter notifications)
          }
      }
      
    • Register the component in AppServiceProvider:
      Livewire::component('custom-topbar', \App\Http\Livewire\CustomTopbar::class);
      
  • Database Notifications

    • Ensure notifications table exists (Laravel’s default migration):
      php artisan migrate
      
    • Beacon automatically reads from this table for non-realtime notifications.
  • Browser Events

    • Listen for Beacon events in JavaScript:
      window.addEventListener('beacon.notification.created', (e) => {
          console.log('New notification:', e.detail);
      });
      
  • Testing

    • Use Laravel’s notification testing helpers:
      $user = User::factory()->create();
      $notification = new TestNotification();
      Notification::fake();
      $user->notify($notification);
      Notification::assertSentTo($user, TestNotification::class);
      

Gotchas and Tips

Pitfalls

  1. Missing Notifiable Trait

    • Error: Call to undefined method App\Models\User::route().
    • Fix: Ensure all notifiable models include use Illuminate\Notifications\Notifiable;.
  2. Broadcasting Not Configured

    • Error: Notifications appear in the database but not in realtime.
    • Fix: Verify broadcasting settings in beacon.php and install Pusher/Reverb:
      composer require pusher/pusher-php-server
      
  3. Channel Mismatch

    • Error: Notifications don’t appear for specific models.
    • Fix: Ensure notifiable_models in beacon.php includes the correct model classes.
  4. Livewire Component Not Found

    • Error: @livewire('beacon::topbar') fails with "Component not found".
    • Fix: Publish views first (php artisan vendor:publish --tag=beacon-views) or register the component manually in AppServiceProvider.
  5. CSRF Token Mismatch

    • Error: Livewire components fail with "CSRF token mismatch".
    • Fix: Ensure your layout includes @csrf and Livewire’s @stack('scripts').

Debugging

  • Check Logs

    • Enable Laravel debugging in .env:
      APP_DEBUG=true
      
    • Tail logs for Beacon events:
      tail -f storage/logs/laravel.log | grep beacon
      
  • Verify Database

    • Inspect the notifications table for pending notifications:
      SELECT * FROM notifications WHERE read_at IS NULL;
      
  • Test Broadcasting

    • Use Laravel Echo’s debug panel:
      Echo.connector.debug = true;
      

Tips

  1. Custom Notification Types

    • Extend BeaconMessage for custom UI:
      class CustomMessage extends BeaconMessage
      {
          public function __construct()
          {
              $this->icon = 'fas fa-bell';
              $this->priority = 'high';
          }
      }
      
  2. Conditional Topbar

    • Show/hide the topbar based on user roles:
      @auth
          @if(auth()->user()->isAdmin())
              @livewire('beacon::topbar')
          @endif
      @endauth
      
  3. Mark All as Read

    • Add a "Mark as Read" button in your inbox:
      // In a Livewire component
      public function markAllAsRead()
      {
          auth()->user()->unreadNotifications()->update(['read_at' => now()]);
      }
      
  4. Localization

    • Translate Beacon’s default strings by publishing the language file:
      php artisan vendor:publish --tag=beacon-lang
      
    • Override in resources/lang/en/beacon.php.
  5. Performance

    • For large-scale apps, lazy-load notifications:
      // In a Livewire component
      public $notifications = [];
      
      public function loadMore()
      {
          $this->notifications = auth()->user()->notifications()->paginate(10);
      }
      
  6. Dark Mode Support

    • Customize the topbar for dark themes:
      @if(config('beacon.dark_mode'))
          <div class="bg-gray-800 text-white">
              @livewire('beacon::topbar')
          </div>
      @else
          <div class="bg-white">
              @livewire('beacon::topbar')
          </div>
      @endif
      
  7. Event Listeners

    • Trigger Beacon notifications from events:
      use Illuminate\Support\Facades\Event;
      
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle