Laravel's soft deletes feature helps maintain data integrity by keeping deleted records in your database. However, there are times when you need to permanently remove these records. The new forceDestroy method simplifies this process, eliminating the need to first retrieve the model before permanent deletion.
This method is particularly useful when performing cleanup operations, managing user data for privacy compliance, or implementing moderation systems where certain records need to be completely removed from the database.
use App\Models\Post;// Single record permanent deletionPost::forceDestroy($id);// Multiple recordsPost::forceDestroy([$id1, $id2, $id3]);
Let's explore a practical example of a data cleanup 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' => 'No inactive users to purge']; } // Cleanup related content first $contentCount = Content::onlyTrashed() ->whereIn('user_id', $inactiveUsers) ->count(); Content::whereIn('user_id', $inactiveUsers) ->forceDestroy(); // Permanently remove user accounts $userCount = User::forceDestroy($inactiveUsers); Log::info('Completed user data purge', [ 'users_removed' => $userCount, 'content_removed' => $contentCount ]); UserDataPurged::dispatch($inactiveUsers); return [ 'users_purged' => $userCount, 'content_purged' => $contentCount, 'message' => "Successfully purged {$userCount} inactive user accounts" ]; }}
The forceDestroy method streamlines permanent deletion operations, making your code cleaner and more efficient when managing soft-deleted records.
