Skip to content

Instantly share code, notes, and snippets.

@dinhquochan
Last active December 3, 2018 04:37
Show Gist options
  • Save dinhquochan/8e764db57b422cd0710e498e551c4a5b to your computer and use it in GitHub Desktop.
Save dinhquochan/8e764db57b422cd0710e498e551c4a5b to your computer and use it in GitHub Desktop.
GroupBy Laravel Posts by Year and Month
<?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