20 September 2023

How to delete previous image on update new image or delete record in laravel?

Delete previous image on update new image or delete record in laravel

Laravel Model

public function getProfileImageAttribute($profile_image)

    {

        if(!empty($profile_image))

        {

            return $filepath = URL::to('/') . '/public/upload/' . $profile_image;

        }

    }


    // Custom method to get the original unmodified URL

    public function getOriginalProfileImageAttribute()

    {

        return $this->attributes['profile_image'];

    }


    function deleteProfileImage(){

        $model = $this;

        // Check if the avatar attribute is changing

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

            // Delete the previous profile image if it exists

            $previousFile = $model->getOriginal('original_profile_image');

            if (!empty($previousFile) && Storage::disk('uploads')->exists($previousFile)) {

                // Delete the file

                Storage::disk('uploads')->delete($previousFile);

            }

        }

    }


    protected static function boot()

    {

        parent::boot();


        static::updating(function ($model) {

            $model->deleteProfileImage();

        });

        static::deleting(function ($model) {

            // Delete the previous profile image if it exists

            $previousFile = $model->getOriginal('original_profile_image');

            if (!empty($previousFile) && Storage::disk('uploads')->exists($previousFile)) {

                // Delete the file

                Storage::disk('uploads')->delete($previousFile);

            }

        });

    } 

No comments:

Post a Comment

How to add re-captcha v3 on all Elementor forms using coding?

 Add re-captcha v3 on all Elementor forms using coding add_action('wp_footer',function(){     ?> <script src="https://www...