0

I'm using laravel-page-view-counter to count visits of my products and it's working just fine, what i need to do is to get list of top 10 products by their visits (get 10 products which has largest number of visits).

Here is what I have:

$visits = Product::join('page-visits', function ($join) {
  $join->on('products.id', '=', 'page-visits.visitable_id');
})->get();
$sorted = $visits->sortBy(function ($product, $key) {
  return count($product['visits']);
});

But It return from lowest product visits to highest one (it shows product with 0 visit till product with 100 visits) I need reverse method of that to show (product with 100 visits first).

3
  • It's quit difficult to understand, if you use simple raw query it will be easier Commented Dec 20, 2017 at 4:16
  • @SagarGautam $visits I get my products with their visits in ` page-visits` table. $sorted I sorted my $visits query. is it difficult? Commented Dec 20, 2017 at 4:18
  • Okay, I've added my answer take a moment to try it if any problem feel free to ask :) Commented Dec 20, 2017 at 4:26

1 Answer 1

3

You can do it easily with query builder and some raw queries like this:

$visits = DB::table('products')
            ->join('page-visits','products.id','=','page-visits.visitable_id')
            ->select(DB::raw('count(visitable_id) as count'),'products.*')
            ->groupBy('id')
            ->orderBy('count','desc')
            ->take(10)
            ->get();

I hope you will understand.

Sign up to request clarification or add additional context in comments.

7 Comments

Ok its seems working but now i'm not able to get number of visits for each product it give me error of Undefined property: stdClass::$page_visits_formatted before i could get visits like {{$visit->page_visits_formatted}}
you should use {{$visit->count}} instead of {{$visit->page_visits_formatted}} for that since count contains total no of visits in the query i've added above
and this count will be formatted or no? formatted is like 1.000 if not is like 1000
@mafortis pardon me, I don't understand what you are saying about formatting :)
Bro formatted count will return numbers with . (dot) if number is bigger than 3 digit example 1.000.000 as you see after each 3 digit has one dot.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.