Ecommerce Recently Viewed Products

Published 1 year ago by devonian

Hello, first time posting on here so please go gentle on me :) I've been asked to build a recently viewed product list into my ecommerce application - though I'm a little stumped as to how to go about integrating this.

Any suggestions or advice? I did think middleware might be an option...?

Thanks in advance!

martinbean

@devonian What’s the brief for the feature? If it’s just showing any one user the products they last viewed, then you can just keep an array in the session, and then retrieve those products in a “recently viewed” list.

class ProductController extends Controller
{
    public function show(Product $product)
    {
        // Push product ID to session
        session()->push('products.recently_viewed', $product->getKey());

        return view('product.show', compact('product'));
    }
}
class RecentlyViewedProductsViewComposer
{
    public function compose(View $view)
    {
        $products = session()->get('products.recently_viewed');

        $view->with([
            'recentlyViewed' => Product::find($products),
        ]);
    }
}
devonian

Hi martinbean,

Thanks for your prompt reply - much appreciated. That's a big help, thank you for pointing me in the right direction.

The brief is to display the last eight most recently viewed products globally, just above the footer of the site...

Thanks in advance!

ajitdas

@martinbean Hi, martin , so if want to get only the latest 10 or 15 product max how can i do so?

martinbean

@ajitdas The same way you would limit any other Eloquent query:

Product::whereIn('id', $products)->take(10)->get()
arukomp

and don't forget to order by latest it needed :)

Product::whereIn('id', $products)->latest()->take(10)->get()

// or 

Product::whereIn('id', $products)->orderBy('created_at', 'desc')->take(10)->get()
ajitdas

@martinbean @arukomp yes, thank you guyz :))

Please sign in or create an account to participate in this conversation.