I'm new to Laravel and I've been struggling too long with this now, tried to search SO and google for information but can't solve this.
I'm creating blog and need to make some kind of navigation/archive which displays year and months and how many blog posts there have been per year and invidual month. By clicking those years/months I would then display posts during that time period on different view.
I want them to be displayed in the view like this:
2015 (10)
January(3)
February(3)
March(3)
April(1)
2014 (2)
May(1)
June(1)
And so on.
I got database query like this:
$links = \DB::table('posts')
->select(\DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) id'))
->where('active',1)
->groupBy('year')
->groupBy('month')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->get();
Which gives me table like this:
array:3 [
0 => {#275
+"year": "2015"
+"month": "10"
+"month_name": "October"
+"id": "3"
}
1 => {#274
+"year": "2015"
+"month": "9"
+"month_name": "September"
+"id": "1"
}
2 => {#273
+"year": "2014"
+"month": "8"
+"month_name": "August"
+"id": "1"
}
]
How can I print it on my view like I described? If I go through the array in views like this:
@foreach($links as $link)
<h3 class="text-uppercase"><a href="{{ url('blog/'.$link->year) }}">{{ $link->year }}</a></h3>
<p><small class="blog_date"><a href="{{ url('blog/'.$link->year.'/'.$link->month) }}">{{ $link->month_name }} ({{ $link->id }}) </a></small>
@endforeach
I tried to use foreach-loop in my Controller to create another array from DB-results where structure would be in correct form and I could just use foreach to print it on the view, but couldn't get it work.
I know I'm near the solution, but I'm still learning. Please someone tell me which is the best way to do this.