Laravel 5.4:获取带收藏状态的商品并为用户展示收藏商品
实现商品收藏状态展示与收藏功能方案
我来帮你梳理下实现这个功能的具体步骤,咱们从控制器到视图一步步调整,完美实现登录用户的收藏状态识别与收藏操作~
一、调整控制器的商品查询逻辑
你当前用with('favorite')会加载该商品的所有用户收藏记录,但咱们只需要当前登录用户的收藏状态就行,所以给关联查询加个过滤条件,精准获取当前用户的收藏:
$products = Product::where('quantity', '>', 0) ->with(['favorite' => function ($query) { // 已登录时,只加载当前用户的收藏记录 if (auth()->check()) { $query->where('user_id', auth()->id()); } else { // 未登录时直接返回空集合,避免多余数据 $query->where('user_id', 0); } }]) ->orderBy('price', $sort) ->get();
调整后,每个商品的$product->favorite要么是当前用户的那条收藏记录(已收藏),要么是空集合,后续判断起来就很方便啦。
二、视图层动态展示收藏状态
在循环渲染商品的视图里,咱们通过判断$product->favorite是否有数据,来展示不同的状态和操作:
@foreach($products as $product) <div class="product-card"> <!-- 商品基础信息展示 --> <h4>{{ $product->name }}</h4> <p class="price">¥{{ $product->price }}</p> <!-- 收藏状态区域 --> @if(auth()->check()) @if($product->favorite->isNotEmpty()) <span class="tag-favorited">已收藏</span> @else <!-- 未收藏时显示收藏按钮 --> <form action="{{ route('favorites.store') }}" method="POST"> @csrf <input type="hidden" name="product_id" value="{{ $product->id }}"> <button type="submit" class="btn-favorite">加入收藏</button> </form> @endif @else <!-- 未登录用户提示登录 --> <a href="{{ route('login') }}" class="btn-prompt-login">登录后即可收藏</a> @endif </div> @endforeach
三、补充收藏操作的控制器方法(如果还没实现)
最后咱们还需要一个处理收藏请求的方法,比如新建一个FavoritesController,写个store方法:
public function store(Request $request) { // 先判断用户是否登录 if (!auth()->check()) { return redirect()->route('login')->with('tip', '请先登录再收藏商品哦'); } // 检查是否已经收藏过,避免重复创建记录 $hasFavorited = Favorite::where('user_id', auth()->id()) ->where('product_id', $request->product_id) ->exists(); if ($hasFavorited) { return back()->with('tip', '你已经收藏过这个商品啦'); } // 创建新的收藏记录 Favorite::create([ 'user_id' => auth()->id(), 'product_id' => $request->product_id, ]); return back()->with('tip', '收藏成功!'); }
别忘了在路由里配置好收藏的POST路由哦,比如:
Route::post('/favorites', [FavoritesController::class, 'store'])->name('favorites.store');
这样一套流程走下来,就能完全实现你想要的功能啦~
内容的提问来源于stack exchange,提问作者Yousef Altaf
相关产品推荐
相关产品推荐

