【问题标题】:How to delete image with ajax in laravel如何在laravel中使用ajax删除图像
【发布时间】:2020-02-20 03:11:05
【问题描述】:

我正在尝试从我的产品表中删除一条记录,每个产品都有一张图片。我不知道如何从存储图像的文件中删除图像。

Product.js

$(document).ready(function() {    

    $("#btn-delete").click(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: 'DELETE',
            url: '/product/' + $("#frmDeleteProduct input[name=product_id]").val(),
            dataType: 'json',
            success: function(data) {
                $("#frmDeleteProduct .close").click();
                window.location.reload();
            },
            error: function(data) {
                console.log(data);
            }
        });
    });
});

function deleteProductForm(product_id) {
    $.ajax({
        type: 'GET',
        url: '/product/' + product_id,
        success: function(data) {
            $("#frmDeleteProduct #delete-title").html("¿Do you want to delete this product (" + data.products.name + ")?");
            $("#frmDeleteProduct input[name=product_id]").val(data.products.id);
            $('#deleteProductModal').modal('show');
        },
        error: function(data) {
            console.log(data);
        }
    });
}

ProductController.php

我读到我需要在我的控制器 File::delete('img/products/' . $image); 中放入类似的东西,但我现在不知道如何。

public function destroy($id)
    {

        //File::delete('img/products/' . $image); 
        $products = Product::destroy($id);

        return response()->json([
            'error' => false,
            'products'  => $products,
        ], 200);
    }

【问题讨论】:

  • 在你的destroy方法中,你应该检查数据库中是否存在具有该id的图像,如果存在,获取图像路径,然后使用PHP的“unlink”方法或使用Storage::delete函数与您的文件的路径。
  • 我用这个id来验证产品。图像具有不同的名称。我应该怎么做? @AliKhalili
  • 删除商品前需要先获取商品图片,然后Storage::delete($product->image),然后才能继续删除商品

标签: javascript php html ajax laravel


【解决方案1】:

您需要在保存图像时将完整路径作为参数传递给File::delete()。例如,如果您的图片在子目录img/products/ 的laravel 存储路径中,并且图片的名称是带有.jpg 扩展名的产品的id,您可以这样做:

public function destroy($id)
{
    $fullImgPath = storage_path("img/products/$id.jpg");
    if(File::exists($fullImgPath)) {
        File::delete($fullImgPath);
    }

    $products = Product::destroy($id);

    return response()->json([
        'error' => false,
        'products'  => $products,
    ], 200);
}

但如果你的Product 模型中有图片的名称,你可以这样做:

public function destroy($id)
{
    $product = Product::find($id);

    $fullImgPath = storage_path("img/products/".$product->image_name);
    if(File::exists($fullImgPath)) {
        File::delete($fullImgPath);
    }

    $product->delete();

    return response()->json([
        'error' => false,
        'products'  => $product->id,
    ], 200);
}

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多