You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel实现仅已收藏商品心形图标变红的问题排查

Laravel收藏夹图标批量变红问题修复方案

问题核心:当前后端返回的是全局布尔值,仅判断用户是否收藏了这批商品中的任意一个,而非每个商品是否单独被收藏;前端用这个全局值控制所有图标颜色,导致一收藏就全变红。

后端代码修改(Laravel)

将全局判断改为给每个商品添加独立的收藏标记:

$productData = $select_pro->get();

// 获取当前用户已收藏的这批商品ID集合
$wishlistProductIds = DB::table('wishlist')
    ->whereIn('pid', $productData->pluck('id'))
    ->where('userid', $userId)
    ->pluck('pid')
    ->toArray();

// 给每个商品追加「是否在收藏夹」的标记
$productData->transform(function ($product) use ($wishlistProductIds) {
    $product->in_wishlist = in_array($product->id, $wishlistProductIds);
    return $product;
});

$subImagesData = DB::table('images')->whereIn('product_id', $productData->pluck('id'))->get();

$data = [
    'products' => $productData,
    'sub_images' => $subImagesData,
];

return response()->json(['data' => $data]);

前端代码修改(Blade/JS)

遍历商品时,使用每个商品自身的in_wishlist标记控制图标颜色,同时移除重复的ID(避免DOM冲突):

// 遍历商品数组生成卡片
response.data.products.forEach(function(product) {
    const productId = product.id;
    const isInWishlist = product.in_wishlist; // 取当前商品的独立标记
    let cardHtml = '';
    
    cardHtml += '<a href="#" class="addtowishlist" data-productid="' + productId + '">';
    cardHtml += '<i class="fa fa-heart fa-2x addtowishliststyle" aria-hidden="true" style="color: ' + (isInWishlist ? '#8B0000' : 'white') + '"></i>';
    cardHtml += '</a>';
    
    // 将生成的卡片插入页面容器
    // document.getElementById('product-container').innerHTML += cardHtml;
});

内容的提问来源于stack exchange,提问作者Meera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:43:05