Since file deletion is often irreversible, this Laravel package queues file deletions within a database transaction, allowing for rollback in case of errors.
Let's say you have a use case that resembles this:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
DB::transaction(function () use ($images) {
/** @var \App\Models\Image $image */
foreach ($images as $image) {
$image->delete();
Storage::delete($image->path);
// more logic ...
}
});
If an error occurs while handling the second image, the database rows for both the first and second images will be rolled back by the transaction, but the actual file for the first image will be gone forever.
use Illuminate\Support\Facades\Storage;
use Medilies\RmQ\Facades\RmQ;
RmQ::transaction(function () use ($images) {
/** @var \App\Models\Image $image */
foreach ($images as $image) {
$image->delete();
RmQ::stage($image->path);
// more logic ...
}
});
RmQ::delete();
This way, the file deletion is queued and the deletion can be fully rolled back.
Requirements:
- PHP >= 8.2
- Laravel >= 10 (not tested on older versions).
Install the package via composer:
composer require medilies/rm-q
Publish and run the migrations with:
php artisan vendor:publish --tag="rm-q-migrations"
php artisan migrate
You can publish the config file with:
php artisan vendor:publish --tag="rm-q-config"
use Medilies\RmQ\Facades\RmQ;
RmQ::transaction(function () {
// ...
$files = '/path/to/file';
// or
$files = [
'/path/to/file1',
'/path/to/file2',
];
// ...
RmQ::stage($files);
});
Important
If you use DB::transaction
instead of RmQ::transaction
make sure to not call Rmq::stage
within a loop since each call will perform a database insertion.
Using the middleware will optimize the performance further more by not doing any query until the end of the request performing a total of 1 to 3 queries.
Delete the files staged by the singleton:
use Medilies\RmQ\Facades\RmQ;
RmQ::delete();
Delete all the staged files:
use Medilies\RmQ\Facades\RmQ;
RmQ::deleteAll();
Delete all the staged files using a command (you can also schedule it):
php artisan rm-q:delete
deleteAll
takes into consideration theafter
config to fetch staged entries.
Automatically delete the staged files at the end of the request using the middleware:
use Medilies\RmQ\Middleware\RmqMiddleware;
Route::put('edit-user-details', function (Request $request) {
// ...
})->middleware(RmqMiddleware::class);
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.