cloudinary-community / cloudinary-laravel

Laravel SDK for Cloudinary
MIT License
255 stars 71 forks source link

Delete previous image and upload new #67

Closed Gianluigi081 closed 1 year ago

Gianluigi081 commented 2 years ago

if($request->hasFile('image')){

        $public_id = Cloudinary::upload('public_id');

        $url = Storage::disk('cloudinary')->url($public_id);

        $image_exist = Category::select('image')->where($public_id);

        Cloudinary::destroy($image_exist);

        Cloudinary::upload($request->file('image')->getRealPath(), ['folder' => 'Categories',]);

        $image = $request->file('image')->getRealPath();
    }

I have also tried like this:

        Cloudinary::destroy($article->image);

        $article['image'] = Cloudinary::upload($request->file('image')->getRealPath(),[
            'folder' => 'Articles',
        ])->getSecurePath();

And so this method works but then it doesn't show me the images in Laravel, but if I delete and update the image in Cloudinary:

      if($request->hasFile('image')){

        Cloudinary::destroy($article->image);

        $article['image'] = Cloudinary::upload($request->file('image')->getRealPath(),[
            'folder' => 'Articles',
        ])->getPublicId();

    }
Gianluigi081 commented 2 years ago

solution:

  1. First split the array by /, then get the last position and split it to remove the .jpg
  2. In this way the public id is obtained

`<?php

$string = "https://res.cloudinary.com/djoqnuant/image/upload/v1648822921/Profiles/qttjxqfcfhrwttzyuivo.jpg";

$token = explode('/', $string);

var_dump($token);

$token2 = explode('.', $token[sizeof($token)-1]);

var_dump($token2[0]);

?>`

In Laravel, to delete we use the Cloudinary::destroy('NameFolder/$token[0]) method. The name of the folder will go as long as it is not in the root.

image