Daniel D Daniel D - 1 month ago 10
PHP Question

Return posts with most views in laravel 5.2

I'm working on a feature that is supposed to pull in the top 8 most viewed posts from a database. The code I'm using isn't quite returning what I need and I'm not sure why this is happening. My database row name is

. The code I'm using is below:

$most_populars = \App\Post::where('status', '=', 'PUBLISHED')->get()->sortByDesc('views');

When I use this, I get an array of 123 posts back which is what I expect. So next I use a foreach loop to get the views like this:

foreach ($most_populars as $most_popular) {

When I use the dd() inside of the foreach loop, I get the post with the most views, but I only get the first one. Why is this? Shouldn't I be seeing the view count for 123 other posts? Any help I can get is a great help =) Thanks guys.


dd() will kill the script. The function itself looks like this:

function dd()
    array_map(function($x) { (new Dumper)->dump($x); }, func_get_args());


Note the die at the end. If you want to get each value, then echo it or log it.