Search code examples
phplaravelcloudinary

Get public id of an image to delete


I upload images to cloudinary using upload method:

    public function store(StoreProductRequest $request)
    {
     
        $name = cloudinary()->upload($request->file('image')->getRealPath())->getSecurePath();
        Product::create([
             ...
            "imageUrl" => $name,
        ]);
    }

This will save the image cloudinary URL in imageUrl field, in update method, I want to get the public ID of the image of the product being updated if present:

    public function update(UpdateProductRequest $request, Product $product)
    {
        $imagePublicId = ??;
        if($request->input('image')){
           Cloudinary::destroy($imagePublicId);
        }
        ...
    }

How to get the public ID of the image and delete it?


Solution

  • Check the official documentation for the upload response here

    You can get public_id, asset_id, and more. You just have to get the response first like this

    $response = cloudinary()->upload($request->file('image')->getRealPath());
    

    and use the response to get the SecurePath and PublicID.

    Apart from that, I have another solution that can be helpful to you check this GitHub thread

    Which says call cloudinary()->getPublicId() after cloudinary()->upload(....) like this

    $name = cloudinary()->upload($request->file('image')->getRealPath())->getSecurePath();
    $public_id = cloudinary()->getPublicId();