There is some method in laravel 5 to determine the 5 most elements that have been inserted into a database table.
There is some method in laravel 5 to determine the 5 most elements that have been inserted into a database table.
There is no such thing in Laravel, neither in the Query Builder nor in Eloquent, it has to be done in a somewhat manual way:
DB::table('comentarios')->select('post_id', DB::raw('COUNT(post_id) AS posts'))
->groupBy('post_id')
->orderBy('posts', 'DESC')
->limit(5)
->get();
However there is little hope if you have established relationships with this table, for example posts related to comments, which would allow us to count the number of comments in the relationship (assuming we want to count the number of comments) and order such a count :
Post::withCount('comentarios')
->orderBy('comentarios_count', 'desc')
->take(5)
->get();
raise it in this way reviewing your answer:
$ventas = VentasProductos::withCount('producto')
->orderBy('producto_count', 'desc')
->take(5)
->get();
but in the view it shows me the repeated elements, I believe this line of code but it does not delete one of the repeated elements:
if($ventas){
foreach($ventas as $key=>$venta){
if(array_key_exists($venta->id, $ventas)){
unset($ventas[$key]);
}
}
}