Deleting Files from Storage in Laravel Filament PHP - Emon Shah
Special Offer: 30% Discount for First-Time Customers! Get 30% off on your first website development project with us. Don't miss out on this great opportunity!

Deleting Files from Storage in Laravel Filament PHP

Learn to delete files/images from storage in Laravel Filament using observers. Handle single/multiple models with force delete and proper cleanup.
Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated
Laravel Filament PHP


In Laravel applications, managing file uploads and deletions is crucial for ensuring clean storage and maintaining data consistency. When using Filament PHP, you’ll often deal with file uploads. However, Laravel doesn’t automatically delete files from the storage when records are deleted. This guide demonstrates how to handle file deletions using Observers, both for single models and for multiple models, effectively and cleanly.


Prerequisites

  1. Laravel Application: Make sure you have a Laravel application set up.

  2. Filament Admin: Install Filament Admin in your project.

  3. File Upload: Use Filament’s file upload field for managing uploaded files.

  4. Storage Setup: Ensure the storage:link command is executed to link storage to the public directory:  

php artisan storage:link


Single Model File Deletion Using Observers

For handling file deletion when working with a single model (e.g., Slider), Laravel’s model observers can be used. Observers allow you to hook into the model lifecycle events.

Step 1: Create an Observer

Run the following command to create an observer:

php artisan make:observer SliderObserver --model=Slider 


This will generate a file at app/Observers/SliderObserver.php.

Step 2: Implement File Deletion in the Observer

Modify the SliderObserver as follows:

namespace App\Observers;


use App\Models\Slider;

use Illuminate\Support\Facades\Storage;


class SliderObserver

{

    // Delete the image only on force delete

    public function deleting(Slider $slider)

    {

        if ($slider->isForceDeleting() && $slider->image) {

            Storage::disk('public')->delete($slider->image);

        }

    }


    // Handle old image cleanup on update

    public function saving(Slider $slider)

    {

        if ($slider->isDirty('image')) {

            $originalImage = $slider->getOriginal('image');

            if ($originalImage && Storage::disk('public')->exists($originalImage)) {

                Storage::disk('public')->delete($originalImage);

            }

        }

    }

}


Step 3: Register the Observer

Register the observer in app/Providers/EventServiceProvider.php:

use App\Models\Slider;

use App\Observers\SliderObserver;


public function boot()

{

    Slider::observe(SliderObserver::class);

}


How It Works:

  • Deleting Event: Deletes the file when a record is force deleted.

  • Saving Event: Removes the old file if the image attribute is updated.


Handling File Deletion for Multiple Models

If you have multiple models requiring similar file deletion logic (e.g., Slider, Course), you can use a reusable trait.

Step 1: Create a Reusable Trait

Create a trait named HandlesImageDeletion

namespace App\Traits;


use Illuminate\Support\Facades\Storage;


trait HandlesImageDeletion

{

    protected static function bootHandlesImageDeletion()

    {

        static::deleting(function ($model) {

            if (method_exists($model, 'isForceDeleting') && $model->isForceDeleting()) {

                if ($model->image && Storage::disk('public')->exists($model->image)) {

                    Storage::disk('public')->delete($model->image);

                }

            }

        });


        static::saving(function ($model) {

            if ($model->isDirty('image')) {

                $originalImage = $model->getOriginal('image');

                if ($originalImage && Storage::disk('public')->exists($originalImage)) {

                    Storage::disk('public')->delete($originalImage);

                }

            }

        });

    }

}


Step 2: Use the Trait in Your Models

Include the trait in each model that requires image deletion:

namespace App\Models;


use Illuminate\Database\Eloquent\Model;

use App\Traits\HandlesImageDeletion;


class Slider extends Model

{

    use HandlesImageDeletion;

    // Other model properties

}


class Course extends Model

{

    use HandlesImageDeletion;

    // Other model properties

}


This approach allows you to share the same deletion logic across multiple models.


Important Notes

  1. Soft Deletes:

    • Ensure that the SoftDeletes trait is included in your models if you want to utilize the trash feature.

    • Files will only be deleted on force delete, ensuring recoverability from the trash.

  2. Public Disk:

    • This guide assumes that you’re storing files in the public disk. Update the disk name if you’re using a different storage disk.

  3. File Existence Check:

    • Always check if a file exists before attempting to delete it to avoid unnecessary errors.

  4. Observer vs Trait:

    • Use observers for single-model scenarios.

    • Use traits for multi-model scenarios to avoid code duplication.

  5. Filament Form Integration:

    • Use the Filament FileUpload or ImageUpload fields to handle file uploads in the admin panel.



Summary

You can handle file deletions in Laravel Filament PHP effectively using:

  1. Observers for single models.

  2. Traits for multiple models requiring the same functionality.

Both methods ensure that your storage remains clean and prevents unused files from lingering. With this setup, your Laravel application will efficiently manage file uploads and deletions, even in complex scenarios.

 

 

 

 

إرسال تعليق

💻 Need a Professional Website?
We offer modern and responsive website development services tailored to your needs. From business to e-commerce, we've got you covered! Visit My Website to learn more.

Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.