Code lấy thông tin bài viết đã xem qua
Code này có thể tùy chỉnh để lưu thông tin giỏ hàng ,Mình không lưu ở session hay cookie ,Mình khám phá theo 1 cách mới đó là lưu ở cache .Lý do mình lưu ở cache là để phù hợp với việc bài viết gần nhất sẽ được ưu tiên lấy theo người dùng sau đó mới đến fingerprint :
<?php
namespace App\Services;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class RecentPostService
{
    public string $redis_store, $cache_key;
    public  $data;
    public int $max_save,$max_day;
    public function __construct($data)
    {
        $this->cache_key = env('APP_NAME').'.recent_posts.';
        $this->data = $data;
        $this->redis_store = 'redis';
        $this->max_save = 20;
        $this->max_day = 20;
    }
    public function save(){
        // kiểm tra xem người dùng đã đăng nhập chưa
        if(Auth::check())
        {
            $user_id = Auth::id();
            $this->cache_key .= 'user_id.'.$user_id;
            $recentposts = Cache::store($this->redis_store)->get($this->cache_key,[]);
            // kiem tra xem da co ban ghi trong mang chua
            $recentposts = array_filter($recentposts,function ($post){
                return $post['post_id'] !== $this->data['post_id'];
            } );
            // thêm vào đầu
            array_unshift( $recentposts,[
                'user_id' => $user_id,
                'post_id' => $this->data['post_id'],
                'created_at' => $this->data['created_at'],
            ]);
            array_slice($recentposts,0,$this->max_save);
            // lưu lại vào cache
            Cache::store($this->redis_store)->put($this->cache_key,$recentposts,Carbon::now()->addDays($this->max_day));
        }else{
            $this->cache_key .='fingerprint.' .$this->data['fingerprint'];
            $recentposts = Cache::store($this->redis_store)->get($this->cache_key,[]);
            // dùng array_filter để giữ lại các post_id không trùng
            $recentposts = array_filter($recentposts,function ($post){
                return $post['post_id'] !== $this->data['post_id'];
            });
            array_unshift($recentposts,[
//                'fingerprint' => $this->data['fingerprint'],
                'post_id' => $this->data['post_id'],
                'created_at' => $this->data['created_at'],
            ]);
            Cache::store($this->redis_store)->put($this->cache_key,$recentposts,Carbon::now()->addDays($this->max_day));
            echo 'Lưu thành công';
        }
    }
}
Các bạn có thể xem qua và áp dụng ,bạn cũng có thể nghĩ theo cách này để tạo giỏ hàng với cache
 
                                    
                 
                 
                 
                