0
0

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.

PHP if文とcount()の混合条件の作成

Posted at

はじめに

今回は基本的な投稿システムが完了したので少しこだわりを入れて備忘録として投稿いたします。これを利用してlaravelに組み込みます。

今回の条件

  1. 1件以上のコメントがある場合は現在〇〇件コメント数という風に表示
  2. コメントが0件の場合は現在〇〇件コメント数を非表示にする

これらの条件を使用するにはif文とcount()の両方を使用することになります。以下にサンプルを掲載します。

if文の構文

if.php

$value1 = 200;
$value2 = 100;

if ($value1 > $value2){
  echo 'value1はvalue2より大きい';
  $value2 = $value1;
}

countの構文

count.php

$collection = collect(['鈴木', '佐藤', '田中']);
echo $collection->count();  // 3

上記の条件を纏めたコード

sample.php

@if ($post->comments->count() >= 1)
<p>
  <span class="badge badge-primary">
    現在のコメント数 {{ $post->comments->count() }}
  </span>
</p>
@endif

“スクリーンショット” 2021-03-29 17.29.14.jpg

解説

今回は各々が投稿した投稿内容の詳細にコメントを掲載するようになっています。
$postは投稿の変数になります。commentsはPost.modelのcommentsを表しています。
>= 1で1件以上のコメントがある場合は不等号を使用して表示させる様にしています。

Post.php

    public function comments()
    {
        // 投稿は複数のコメントを持つ
        return $this->hasMany('App\Models\Comment');
    }
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?