<?php
 namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class EmailMarketingList extends Model { use HasFactory; protected $fillable = [ 'name', 'description', 'provider', 'remote_id', 'status', 'subscribers_count', 'default_from_name', 'default_from_email', 'default_reply_to', ]; protected $casts = [ 'subscribers_count' => 'integer', ]; public function campaigns() { return $this->hasMany(EmailCampaign::class, 'email_marketing_list_id'); } public function subscribers(): BelongsToMany { return $this->belongsToMany( EmailMarketingSubscriber::class, 'email_marketing_list_subscriber', 'email_marketing_list_id', 'email_marketing_subscriber_id', )->withPivot(['joined_at', 'source'])->withTimestamps(); } public function recountSubscribers(): void { $count = $this->subscribers()->where('email_marketing_subscribers.status', 'subscribed')->count(); $this->updateQuietly(['subscribers_count' => $count]); } } 