6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】一覧表示画面でDBのデータ有無で表示を切り替える方法(「◯◯はありません」と表示しよう)

Last updated at Posted at 2021-03-06

概要

よくあるコンテンツ共有サービスの一覧画面で

DBにデータが 動作・表示
ある DBのデータを一覧表示
ない 「データはありません」というメッセージを表示する

こんなよくある機能を実装する方法をちょっと詳しくまとめます。

環境

$ composer -V
Composer version 1.10.20 2021-01-27 15:41:06

$ php artisan --version
Laravel Framework 6.20.16

一覧表示画面でDBのデータ有無で表示を切り替える方法

手順はざっくりこんな感じ

  • ルーティング設定
  • Controller
  • Viewで切り替えを実装(←ここがメイン)

※DBからのデータ取得はシンプルなものにするのでModelではなくControllerで処理することにします。

ルーティング設定

routes/web.php
Route::get('/', 'ArticleController@index')->name('index');

resourceメソッドで定義しても問題ないです。

Controller

記事テーブル(articles)に対応するArticleモデルを使用してORMを使ってDBからデータを取得するケースを想定。

app/Http/Controllers/ArticleController.php
    /**
     * 記事一覧画面表示
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::all();
        return view('articles.index', compact('articles'));
    }

以下の項目などは本記事では省略してシンプルに全件取得のみにしています。

  • ->with()でN+1問題対策
  • ->orderBy()メソッドでソート
  • ->paginate()でページネーション

Viewで切り替えを実装(←ここがメイン)

今回ControllerでDBからデータを取得する処理は以下のコードで実装しています。

$articles = Article::all();

この$articlesddd()でデバッグしてみます。

スクリーンショット 2021-03-06 10.57.48.png

データの型は"Illuminate\Database\Eloquent\Collection"クラスのオブジェクトです。
all()を使うとCollectionになります)

ddd()についてはこちらの記事で解説しています。
【Laravel6.x〜】デバッグするならdd()?いやいや、ddd()を使おう!!

Collectionでデータの有無を判定する方法は主に以下の3つです。

コード例 データがある データがない
$article->isEmpty() false true
$articles->count() true(1以上) false(0)
$empty(articles->all()) false true

例として、->isEmpty()を使って以下のように書けます。

resources/views/articles/index.blade.php
@if (!$articles->isEmpty())
    {{-- 記事データがDBにある場合の表示内容 --}}
@else
    {{-- 記事データがDBにない場合の表示内容 --}}
@endif

このように書くことによって

・データがある場合:データを一覧表示
・データがない場合:「データはありません」というメッセージを表示

することができます。

注意点

Collectionの場合、文字列の時みたいに以下の書き方をするとうまく条件分岐できないのでご注意ください。

resources/views/articles/index.blade.php
{{-- これだとうまく条件分岐できない --}}
@if (!$articles)
    {{-- 記事データがDBにある場合の表示内容 --}}
@else
    {{-- 記事データがDBにない場合の表示内容 --}}
@endif

まとめ

  • Collectionというクラスがあるのを理解しておくべし
  • 公式ドキュメントの日本語訳(ReaDouble)にメソッドがたんまり書いてあるので見ておくべし(最後に参考に載せてます)

参考

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?