Last active
December 3, 2018 04:37
-
-
Save dinhquochan/8e764db57b422cd0710e498e551c4a5b to your computer and use it in GitHub Desktop.
GroupBy Laravel Posts by Year and Month
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\Post; | |
$posts = Post::query() | |
->selectRaw( | |
'YEAR(`published_at`) as `year`, MONTH(`published_at`) as `month`, MONTHNAME(`published_at`) as `month_name`, COUNT(id) as `posts_count`' | |
) | |
->groupBy('year') | |
->groupBy('month') | |
->groupBy('month_name') | |
->orderBy('year', 'asc') | |
->orderBy('month', 'asc') | |
->get(); | |
$totalPosts = $posts->sum('posts_count'); | |
$groupedPosts = $posts->groupBy('year'); | |
// OUTPUT | |
// $totalPosts -> 1000 | |
// $groupedPosts -> Collection:: [ | |
// 2018 -> Collection:: [ | |
// Post:: [ | |
// 'month_name' -> 'January', | |
// 'posts_count' -> 25, | |
// ] | |
// ] | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment