Quantcast
Channel: 配列タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 757

月別記事一覧と、投稿数表示機能

$
0
0
目次 1.月別集計 2.月別ページ表示 Laravelを使ったブログサイト作成で、月別記事一覧と投稿数を表示させる機能を作ったのでアウトプット記事書いてみます。 ↓ 最終目標はこんな感じです 1. 月別集計 流れとしては、公開中の記事から指定した年の記事を取得し、月別取得&投稿数取得。 あとは blade側で @foreach を使って月と投稿数を表示させていく感じです! where('is_published', 1) を書かないと非公開記事まで表示されてしまうので注意です! PostController.php public function index(): View { ...省略 $year = date('Y'); $monthPosts = $this->Post->findMonthPostCount($year); return view( 'posts.index', [ 'year' => $year, 'monthPosts' => $monthPosts, ] ); } Post.php public function findMonthPostCount($year): Collection { return Post::where('is_published', 1) ->whereYear('created_at', $year) ->orderBy('created_at') ->get() ->groupBy(function ($row) { return $row->created_at->format('m'); //月別取得 }) ->map(function ($day) { return $day->count(); //投稿数取得 }); } index.blade.php ...省略 <h1 class="month-title">月別記事</h1> <button class="button">{{$year}}</button> <div class="card-month"> @foreach($monthPosts as $month => $count) <li class="li-month"> <a href="{{ route('posts.month', [$year, $month]) }}"> {{$year}}/{{ $month }} ({{$count}}) </a> </li> @endforeach これを表示させてみると、こんな感じです! 投稿がある月だけ表示されるのでとても見やすいと思います! 例えば、追加で5月の記事を投稿してみた場合、 こんな感じで5月の記事が追加されます! そのまま URL になっているのでクリックで月別記事一覧に飛べます! <a href="{{ route('posts.month', [$year, $month]) }}"> {{$year}}/{{ $month }} ({{$count}}) </a> 2. 月別ページ表示 月別ページの表示は、 $year $month を引数で渡してあげて指定した月を取得すればOKです! PostController.php public function month(Request $request): View { $year = $request->year; $month = $request->month; $posts = $this->Post->findByCreated($year, $month); return view( 'posts.month', [ 'year' => $year, 'month' => $month, 'posts' => $posts, ] ); } Post.php public function findByCreated(string $year, string $month): LengthAwarePaginator { $posts = Post::where('is_published', 1) ->whereYear('created_at', $year) ->whereMonth('created_at', $month) ->latest()->paginate(9); $posts->load('user', 'tags', 'images'); return $posts; } 完成です! view 側は、 <div id="blog-top"> {{$year}}年 {{$month}}月 の記事一覧</div> みたいな感じにすると年月に対応した表示になるのでわかりやすいと思います! 月別記事一覧は、投稿数が多いブログだと必要になってくると思うのでぜひ参考にしてみてください〜!

Viewing all articles
Browse latest Browse all 757

Trending Articles