store/app/Models/Notification.php

51 lines
1.1 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Guarded(['id'])]
class Notification extends Model
{
// 1. Casting
protected function casts(): array
{
return [
'is_read' => 'boolean',
'read_at' => 'datetime',
];
}
// 2. Scope (grouped by column, then alphabetical)
// Column Group: is_read
#[Scope]
protected function read(Builder $query): void
{
$query->where('is_read', true);
}
#[Scope]
protected function unread(Builder $query): void
{
$query->where('is_read', false);
}
// 3. Other Methods
public function markAsRead(): void
{
if (! $this->is_read) {
$this->update(['is_read' => true, 'read_at' => now()]);
}
}
// 4. Relation
public function user(): BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
}