$activeChannels * @method static where(string $string, PlatformEnum $platform) * @method static orderBy(string $string) * @method static create(array $validated) */ class PlatformAccount extends Model { /** @use HasFactory */ use HasFactory; protected $fillable = [ 'platform', 'instance_url', 'username', 'password', 'settings', 'is_active', 'last_tested_at', 'status' ]; protected $casts = [ 'platform' => PlatformEnum::class, 'settings' => 'array', 'is_active' => 'boolean', 'last_tested_at' => 'datetime' ]; // Encrypt password when storing /** * @return Attribute */ protected function password(): Attribute { return Attribute::make( get: function ($value, array $attributes) { // Return null if the raw value is null if (is_null($value)) { return null; } // Return empty string if value is empty if (empty($value)) { return ''; } try { return Crypt::decryptString($value); } catch (\Exception $e) { // If decryption fails, return null to be safe return null; } }, set: function ($value) { // Store null if null is passed if (is_null($value)) { return null; } // Store empty string as null if (empty($value)) { return null; } return Crypt::encryptString($value); }, )->withoutObjectCaching(); } // Get the active accounts for a platform (returns collection) /** * @return Collection */ public static function getActive(PlatformEnum $platform): Collection { return static::where('platform', $platform) ->where('is_active', true) ->get(); } // Set this account as active (deactivates others for same platform) public function setAsActive(): void { // Deactivate other accounts for this platform static::where('platform', $this->platform) ->where('id', '!=', $this->id) ->update(['is_active' => false]); // Activate this account $this->update(['is_active' => true]); } /** * @return BelongsToMany */ public function channels(): BelongsToMany { return $this->belongsToMany(PlatformChannel::class, 'platform_account_channels') ->withPivot(['is_active', 'priority']) ->withTimestamps(); } /** * @return BelongsToMany */ public function activeChannels(): BelongsToMany { return $this->channels() ->wherePivot('is_active', true) ->orderByPivot('priority', 'desc'); } }