0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-04-02

目次

1.月別集計
2.月別ページ表示

Laravelを使ったブログサイト作成で、月別記事一覧と投稿数を表示させる機能を作ったのでアウトプット記事書いてみます。


↓ 最終目標はこんな感じです
スクリーンショット 2022-04-02 17.39.13.png

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

これを表示させてみると、こんな感じです!
投稿がある月だけ表示されるのでとても見やすいと思います!

スクリーンショット 2022-04-02 19.01.29.png

例えば、追加で5月の記事を投稿してみた場合、
スクリーンショット 2022-04-02 19.14.24.png

こんな感じで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>
みたいな感じにすると年月に対応した表示になるのでわかりやすいと思います!

月別記事一覧は、投稿数が多いブログだと必要になってくると思うのでぜひ参考にしてみてください〜!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0