code16
Published in

code16

Automatically delete read database notifications in Laravel

Photo by Markus Winkler on Unsplash
mysql> describe notifications;
+-----------------+-----------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-----------------+------+-----+---------+-------+
| id | char(36) | NO | PRI | NULL | |
| type | varchar(255) | NO | | NULL | |
| notifiable_type | varchar(255) | NO | MUL | NULL | |
| notifiable_id | bigint unsigned | NO | | NULL | |
| data | text | NO | | NULL | |
| read_at | timestamp | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+-----------------+-----------------+------+-----+---------+-------+
8 rows in set (0,01 sec)
A fake UI that shows database notifications to a logged user
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\MassPrunable;

class Notification extends Model
{
use MassPrunable;

public function prunable(): Builder
{
return static::whereNotNull('read_at')
->where('read_at', '<=', now()->subWeek());
}
}
protected function schedule(Schedule $schedule)
{
$schedule->command('model:prune')->daily();
}
> php artisan model:prune --pretend
1201 [App\Models\Notification] records will be pruned.

--

--

About open source projects at CODE 16

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store