Laravel's soft deletion function maintains data integrity by retaining deleted records in the database. However, sometimes you need to permanently delete these records. The new forceDestroy
method simplifies this process without having to retrieve the model before permanently deleting it.
This method is especially useful when performing cleanup operations, managing user data to comply with privacy compliance, or implementing an audit system that requires the complete removal of certain records from the database.
The following is an example of how to use the forceDestroy
method:
use App\Models\Post; // 永久删除单个记录 Post::forceDestroy($id); // 删除多条记录 Post::forceDestroy([$id1, $id2, $id3]);
Let's look at a practical example of a data cleaning service:
<?php namespace App\Services; use App\Models\User; use App\Models\Content; use Illuminate\Support\Facades\Log; use App\Events\UserDataPurged; class DataCleanupService { public function purgeInactiveUserData(int $monthsInactive = 12) { $inactiveUsers = User::onlyTrashed() ->where('deleted_at', '<', now()->subMonths($monthsInactive)) ->pluck('id'); if ($inactiveUsers->isEmpty()) { return ['message' => '没有需要清理的非活动用户']; } // 首先清理相关内容 $contentCount = Content::onlyTrashed() ->whereIn('user_id', $inactiveUsers) ->count(); Content::whereIn('user_id', $inactiveUsers) ->forceDestroy(); // 永久删除用户帐户 $userCount = User::forceDestroy($inactiveUsers); Log::info('完成用户数据清理', [ '已删除用户数量' => $userCount, '已删除内容数量' => $contentCount ]); UserDataPurged::dispatch($inactiveUsers); return [ '已清理用户数量' => $userCount, '已清理内容数量' => $contentCount, 'message' => "已成功清理 {$userCount} 个非活动用户帐户" ]; } }
forceDestroy
method simplifies permanent deletion operations, making your code more concise and efficient when managing soft delete records.
The above is the detailed content of Permanent Record Deletion with Laravel's forceDestroy. For more information, please follow other related articles on the PHP Chinese website!