Just learned a useful @laravel tip from @PovilasKorop!
When deleting a model and its related file inside a database transaction, don't delete the file immediately.
If the transaction fails, the database rolls back, but the file is already gone.
Instead, use
This keeps file deletion in sync with a successfully committed database transaction. 👌
#php #laravel #sql #database
DB::afterCommit() to delete the file only after the transaction succeeds:
php
DB::transaction(function () use ($post) { $post->delete(); DB::afterCommit(fn () => Storage::delete($post->image_path)); });
commit d1beaef