简体   繁体   中英

Product Latest View return empty array

I want to display the recently viewed products in the details page. I created a table:

    Schema::create('recently_viewed_products', function (Blueprint $table) {
        $table->id();
        $table->integer('product_id');
        $table->string('session_id');
        $table->timestamps();
    });

In my IndexController:

    public function ProductDetails($id){   //display the product page detail
        $product = Product::findOrFail($id);
        $multiImg = MultiImg::where('product_id',$id)->get();

            // Set Session for Recentlty Views Products
            if(empty(Session::get('seasion_id'))){
                $session_id = md5(uniqid(rand(), true));
            } else {
                $session_id = Session::get('session_id');
            }
            Session::put('session_id',$session_id);

            // Insert product in table if not already exists
            $countRecentlyViewedProducts = DB::table('recently_viewed_products')
               ->where(['product_id'=>$id,'session_id'=>$session_id])->count();
            if($countRecentlyViewedProducts==0){
                DB::table('recently_viewed_products')->insert(['product_id'=>$id,'session_id'=>$session_id]);
            }
             //Get Recently Views Prodcuts Ids
             $recentProductIds = Db::table('recently_viewed_products')->select('product_id')
             ->where('product_id','!=',$id)->where('session_id',$session_id)->inRandomOrder()->get()
             ->take(4)->pluck('product_id');
             
             //Get Recently Views Prodcuts
             $recentlyViewedProducts = Product::whereIn('id',$recentProductIds)->get()->toArray();
             //dd($recentProductIds);


        retur nview('frontend.product.product_details',compact('product','multiImg','recentlyViewedProducts','recentProductIds'));
    } // end method

If if click on a product i get the product id and sessionid in the recentlyviewed products table, but im not able to display in the product details page. I just get an empty array.

I guess the problem is with whereIn:

$recentlyViewedProducts = Product::whereIn('id',$recentProductIds)->get()->toArray();

I try to display the products i have clicked on the products details page

//Get Recently Views Prodcuts Ids
             $recentProductIds = Db::table('recently_viewed_products')->select('product_id')
             ->where('product_id','!=',$id)->where('session_id',$session_id)->inRandomOrder()->get()
             ->take(4)->pluck('product_id');

The letter b in DB is in lowercase you should change it to uppercase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM