本文目录导读:

在 Laravel 中清理历史数据,通常是指清理日志文件、会话文件、缓存数据、过期数据库记录(如通知、活动日志、密码重置令牌)等,根据你的具体需求,有以下几种常见且有效的清理方法:
清理 Laravel 日志文件
Laravel 默认将日志按天存储在 storage/logs/ 目录下,随着运行时间增长,日志文件会占用大量磁盘空间。
手动清理:
# 删除指定天数之前的日志文件(Linux/Mac)
find storage/logs/ -name "laravel-*.log" -mtime +30 -exec rm {} \;
# 或直接清空当前日志(不推荐,会丢失近期日志)
> storage/logs/laravel.log
自动化清理方案(推荐):
在 App\Console\Kernel.php 的 schedule 方法中注册任务:
protected function schedule(Schedule $schedule)
{
// 每天凌晨清理30天前的日志文件
$schedule->call(function () {
$files = glob(storage_path('logs/laravel-*.log'));
$now = now()->subDays(30);
foreach ($files as $file) {
if (filemtime($file) < $now->timestamp) {
unlink($file);
}
}
})->daily();
}
然后在服务器上配置 Cron 定时任务执行 php artisan schedule:run。
清理过期数据库记录
常见且需要定期清理的数据表包括:
password_resets(密码重置令牌,通常1小时后失效)personal_access_tokens(Sanctum API 令牌,长期不活跃的)notifications(通知,使用read_at和created_at判断)sessions(数据库驱动的话,清理过期会话)telescope_entries(Laravel Telescope 监控数据)activity_log(活动日志,如使用 spatie/laravel-activitylog 包)
示例:清理密码重置令牌(Laravel 自带命令):
php artisan auth:clear-resets
自定义清理(在 Kernel 中注册):
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
// 每天清理1天前的密码重置令牌
$schedule->call(function () {
DB::table('password_resets')
->where('created_at', '<', now()->subDay())
->delete();
})->daily();
// 清理30天前且已读的通知
$schedule->call(function () {
DB::table('notifications')
->whereNotNull('read_at')
->where('created_at', '<', now()->subDays(30))
->delete();
})->weekly();
// 清理15天前的 Telescope 记录
$schedule->command('telescope:prune --hours=' . (15 * 24))->daily();
}
清理缓存与临时文件
# 清理所有缓存 php artisan optimize:clear # 清理视图缓存 php artisan view:clear # 清理路由缓存 php artisan route:clear # 清理配置缓存 php artisan config:clear # 清理编译后的服务提供者 php artisan clear-compiled
清理会话文件
如果用 file 驱动(默认),会话文件存储在 storage/framework/sessions/:
# 清理超过2小时未修改的会话文件 find storage/framework/sessions/ -type f -mmin +120 -delete
如果用 database 驱动,需要清理 sessions 表:
DELETE FROM sessions WHERE last_activity < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 2 HOUR));
清理上传的临时文件或过期附件
如果用户上传了文件但未提交表单(如拖拽上传但未保存),临时文件通常存放在 storage/app/public/tmp/,建议编写清理脚本:
// Kernel 中注册
$schedule->call(function () {
$files = Storage::disk('public')->files('tmp');
foreach ($files as $file) {
if (Storage::disk('public')->lastModified($file) < now()->subHours(2)->timestamp) {
Storage::disk('public')->delete($file);
}
}
})->hourly();
使用第三方包自动清理
推荐使用 laravel-model-cleanup(适用于 Model 记录清理)或 laravel-activitylog 自带的清理功能。
安装 laravel-model-cleanup:
composer require gmostafa/php-enum # 然后配置需要清理的模型和条件
该包可以在 Model 中配置 $keepClean 属性,自动删除过期记录。
| 数据类型 | 清理周期 | 方法 |
|---|---|---|
| 日志文件 | 每日/每周 | find ... -mtime +30 -delete + Cron |
| 密码重置令牌 | 每日 | auth:clear-resets 或 SQL |
| 通知(已读) | 每月 | SQL DELETE |
| Telescope 监控数据 | 每日 | telescope:prune |
| 会话文件/表 | 每1-2小时 | 文件 mtime 或 SQL 清理 |
| 视图/路由/配置缓存 | 部署时 | optimize:clear |
最关键的是在 Kernel 中注册 scheduled 任务 并通过服务器的 Cron 每分钟调用 php artisan schedule:run,这样可以做到自动、定期的数据清理,避免日志和数据库不断膨胀。