ldc-legaulois/app/Models/Message.php
2024-10-08 12:22:52 +02:00

101 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use App\Casts\NiceDate;
use App\Models\Notification;
use App\Interfaces\Notifiable as INotifiable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class Message extends Model implements INotifiable
{
/**
* The attributes that are mass assignable.
*
* @var array<integer,string>
*/
protected $fillable = [
'message',
'to'
];
/**
* The attributes that should be cast.
*
* @var array<string,string>
*/
protected $casts = [
'message' => 'encrypted'
];
// * RELATIONSHIPS
/**
* BelongsTo customer relation.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function toCustomer(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Customer::class, 'to');
}
/**
* BelongsTo customer relation.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function fromCustomer(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Customer::class, 'from');
}
/**
* MorphOne notification relation.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function notifiable(): \Illuminate\Database\Eloquent\Relations\MorphOne
{
return $this->morphOne(Notification::class, 'notifiable');
}
// * METHODS
/**
* Created at nice date.
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
public function createdAtNiceDate(): \Illuminate\Database\Eloquent\Casts\Attribute
{
return Attribute::make(
get: fn() => (new NiceDate())->get(null, '', $this->created_at, [])
);
}
/**
* Get older messages.
*
* @param integer $days
* @return \Illuminate\Contracts\Database\Eloquent\Builder
*/
public static function getMessagesOlderThan(int $days): \Illuminate\Contracts\Database\Eloquent\Builder
{
return self::query()->where('updated_at', '<', now()->subDays($days));
}
/**
* Convert the model instance to an array.
* ! Make sure we use correct nicedate formater
*
* @return array
*/
public function toArray(): array
{
return array_merge(parent::toArray(), [
'created_at' => $this->created_at
]);
}
}