
“最近浏览商品”功能是电商网站中常见的用户体验优化手段,它能够记录用户访问过的商品,并在后续访问中展示给用户,方便用户回溯和决策。在 laravel 应用中,利用 cookie 是实现这一功能的轻量级且有效的方式,尤其适用于非登录用户。
核心逻辑位于控制器中,负责获取当前商品信息,更新 Cookie 中存储的最近浏览列表,并确保列表的唯一性和数量限制。
首先,我们需要获取当前正在查看的商品的相关信息,例如 ID、标题和 URL。这些信息将作为单个浏览记录存储在 Cookie 中。
// app/Http/Controllers/ProductController.php
use Illuminate\Support\Facades\Cookie;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function show(Request $request, ProductMaterial $product_material)
{
// ... 其他业务逻辑,例如获取商品详情 ...
$num_to_store = 5; // 设置Cookie中存储的最大商品数量
$minutes_to_store = 60 * 24; // 设置Cookie的过期时间,例如24小时
// 构建当前商品的详细信息
$current_page = [
'id' => $product_material->id,
'title' => $product_material->category->title . ' ' . $product_material->title, // 假设有分类标题
'url' => $request->url(),
];
// ... 后续Cookie处理逻辑
}
}接下来是核心的 Cookie 处理逻辑。我们需要从 Cookie 中读取现有数据,解析 JSON,处理当前商品,然后重新编码并写入 Cookie。
// 承接上文 ProductController@show 方法
// 关键点:使用正确的Cookie键名 'recently_viewed_content' 获取数据
$recent = Cookie::get('recently_viewed_content');
$recent = $recent ? json_decode($recent, true) : []; // 如果Cookie不存在或为空,则初始化为空数组
// 遍历现有记录,如果当前商品已存在,则移除旧记录,确保唯一性
foreach ($recent as $key => $val) {
if ($val['url'] == $current_page['url']) {
unset($recent[$key]);
}
}
// 将当前商品添加到数组的末尾(最新浏览的商品)
// 使用时间戳作为键可以方便地进行排序和识别
$recent[time()] = $current_page;
// 限制存储的商品数量
// 如果数量超过预设值,则截取最新浏览的N个商品
if (count($recent) > $num_to_store) {
// array_slice 的第三个参数 true 保持数组的键名
$recent = array_slice($recent, count($recent) - $num_to_store, $num_to_store, true);
}
// 将更新后的数组编码为JSON字符串,并加入到Cookie队列中
Cookie::queue('recently_viewed_content', json_encode($recent), $minutes_to_store);
// 为了在当前请求中立即使用,可以再次从Cookie中获取并解码
// 确保获取的键名与设置的键名一致
$recently_viewed_content = json_decode(Cookie::get('recently_viewed_content'), true);
// ... 将 $recently_viewed_content 传递给视图
return view('products.show', compact('product_material', 'recently_viewed_content'));关键注意事项:
在 Blade 模板中,我们可以轻松地获取并展示最近浏览的商品列表。
{{-- resources/views/products/show.blade.php --}}
@if(isset($recently_viewed_content) && !empty($recently_viewed_content))
<div class="recently-viewed-products">
<h3>最近浏览</h3>
<ul>
@php
// 对数组进行逆向排序,使最新浏览的商品显示在最前面
// krsort() 保持键名,按键名(此处为时间戳)降序排序
krsort($recently_viewed_content);
@endphp
@foreach($recently_viewed_content as $rvc)
<li>
<a href="{{ $rvc['url'] }}">
{{ $rvc['title'] }}
</a>
</li>
@endforeach
</ul>
</div>
@endif注意事项:
通过上述步骤,我们可以在 Laravel 应用中高效地实现“最近浏览商品”功能。核心在于后端控制器中对 Cookie 的正确管理,包括 JSON 数据的编码与解码、去重逻辑、数量限制,以及最重要的——在获取和设置 Cookie 时使用一致的键名。前端 Blade 模板则负责以用户友好的方式展示这些数据。对于需要更复杂功能(如跨设备同步、长期存储)的场景,可以考虑使用会话(Session)或数据库来替代 Cookie。
以上就是在 Laravel 中实现最近浏览商品功能及常见问题解决的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号