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

wnx/laravel-sends

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require wnx/laravel-sends
    

    Publish the migration and config:

    php artisan vendor:publish --provider="Wnx\LaravelSends\LaravelSendsServiceProvider"
    php artisan migrate
    
  2. Enable Tracking: Add the HasSends trait to your Eloquent models:

    use Wnx\LaravelSends\Concerns\HasSends;
    
    class User extends Model
    {
        use HasSends;
    }
    
  3. First Use Case: Send an email and automatically associate it with models:

    Mail::to($user)->send(new ProductReviewMail($product, $user));
    

    The email will now be tracked and linked to both $product and $user.


Where to Look First

  • Config: config/laravel-sends.php (e.g., table name, model associations).
  • Migrations: database/migrations/[timestamp]_create_laravel_sends_table.php (customize if needed).
  • API Docs: Focus on Send facade and HasSends trait methods.

Implementation Patterns

Core Workflows

  1. Associating Models with Emails:

    • Use the HasSends trait on Eloquent models to query sent emails:
      $user->sends()->latest()->take(5)->get(); // Get 5 latest emails for the user
      
    • Pass models to the send() method to auto-associate:
      Mail::to($user)->send(new OrderConfirmationMail($order, $user));
      
  2. Querying Sent Emails:

    • By Model: $user->sends()->where('subject', 'like', '%review%')->get();
    • By Mailable Class:
      Send::forMailClass(OrderConfirmationMail::class)->where('status', 'sent')->get();
      
    • Global Query Builder:
      Send::where('recipient', 'user@example.com')->get();
      
  3. Customizing Email Tracking:

    • Override default behavior in AppServiceProvider:
      use Wnx\LaravelSends\Events\EmailSent;
      
      public function boot()
      {
          EmailSent::listen(function ($event) {
              // Custom logic (e.g., log to external service)
          });
      }
      
  4. Testing:

    • Assert emails were sent and associated:
      $this->assertCount(1, $user->fresh()->sends());
      $this->assertEquals(OrderConfirmationMail::class, $user->sends->first()->mailable);
      

Integration Tips

  • Queue Integration: If using queues, ensure the EmailSent event fires by adding this to your AppServiceProvider:

    Mail::afterSend(function ($message) {
        event(new EmailSent($message));
    });
    
  • Custom Attributes: Attach metadata to emails via the Send facade:

    Mail::to($user)->send(new ProductReviewMail($product, $user))
        ->withMetadata(['campaign_id' => 123]);
    
  • Soft Deletes: Enable soft deletes in the laravel-sends table by adding SoftDeletes to the Send model and configuring the deleted_at column in the migration.


Gotchas and Tips

Pitfalls

  1. Event Listener Conflicts:

    • If EmailSent events are fired multiple times (e.g., due to middleware or other packages), deduplicate logic in the listener or use a queue to avoid duplicates.
  2. Model Association Limits:

    • The package assumes a many-to-many relationship between models and emails. If you need one-to-one or other relationships, extend the Send pivot model or use custom queries.
  3. Queue Delays:

    • If emails are queued, the EmailSent event may fire after the mailable is processed. For immediate tracking, use Mail::send() instead of Mail::queue().
  4. Recipient Overrides:

    • The recipient field in the laravel_sends table defaults to the to address. Override this in the EmailSent listener if using custom recipient logic.

Debugging

  • Missing Records:

    • Verify the EmailSent event is firing by adding a dd() in the listener or checking Laravel logs:
      tail -f storage/logs/laravel.log | grep "EmailSent"
      
    • Ensure the laravel-sends table exists and is writable.
  • Query Issues:

    • Use Send::query()->toSql() to debug raw queries:
      $query = Send::forMailClass(OrderConfirmationMail::class);
      dd($query->toSql(), $query->getBindings());
      

Tips

  1. Custom Columns: Add columns to the laravel_sends table via migration and update the Send model:

    Schema::table('laravel_sends', function (Blueprint $table) {
        $table->string('custom_field')->nullable();
    });
    

    Then access via:

    $send->custom_field;
    
  2. Performance:

    • Add indexes to frequently queried columns (e.g., mailable, recipient):
      Schema::table('laravel_sends', function (Blueprint $table) {
          $table->index('mailable');
          $table->index('recipient');
      });
      
  3. Bulk Operations: Use chunking for large datasets:

    $user->sends()->chunk(100, function ($sends) {
        foreach ($sends as $send) {
            // Process each send
        }
    });
    
  4. Testing:

    • Use Send::flush() to clear test data between tests:
      public function tearDown(): void
      {
          Send::flush();
          parent::tearDown();
      }
      
  5. Extending the Package:

    • Override the Send model to add custom methods:
      namespace App\Models;
      
      use Wnx\LaravelSends\Models\Send as BaseSend;
      
      class Send extends BaseSend
      {
          public function isPromotional()
          {
              return $this->mailable === PromotionalMail::class;
          }
      }
      
    • Bind the extended model in AppServiceProvider:
      Send::swap(new \App\Models\Send());
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle