不明点
LaravelにてSNSアプリを制作中です。投稿一覧ページの各投稿に「良いね」した人の数を表示したいのですが、
取得方法が分からないためアドバイスいただきたいです。
コントローラにて複数の投稿の配列をビューに渡し、bladeファイルのビューで@foreach
で展開しています。
tinker上では$card->good_users()->where('good', 'good')->count();
で取得自体はできましたが、
アプリ内で一つ一つの投稿のカウントをどこで取得するのか?混乱しています。
※前提:Laravel 5.5
###テーブル構成(関連するもののみ記載)
〇Userテーブル
・id
・name
〇Cardテーブル(投稿)
・id
・conetnt
・audience_selector(公開設定)
〇Good中間テーブル(良いね機能)
・user_id
・card_id
・good(good/badの二択)
現在のコード
Card.php
php
1<?php 2namespace App; 3use Illuminate\Database\Eloquent\Model; 4 5class Card extends Model 6{ 7 protected $fillable = ['user_id', 'content', 'audience_selector']; 8 9 public function user() 10 { 11 return $this->belongsTo(User::class); 12 } 13 public function good_users() 14 { 15 return $this->belongsToMany(User::class, 'good', 'card_id', 'user_id')->withTimestamps(); 16 } 17} 18
CardController.php
php
1 public function index() 2 { 3 $cards = Card::where('audience_selector', 'like', 'public')->orderBy('created_at', 'desc')->paginate(20); 4 5 $data = [ 6 'cards' => $cards, 7 ]; 8 9 return view('welcome', $data); 10 }
welcome.blade.php
php
1@extends('commons.app') 2 3@section('content') 4<ul class="list-unstyled"> 5 @foreach ($cards as $card) 6 <li class="media"> 7 <div class="media-body"> 8 <div class="d-flex justify-content-between"> 9 <div>{!! link_to_route('users.show', $card->user->name, ['id' => $card->user->id]) !!}</div> 10 </div> 11 <div> 12 <p class="card-text">{!! nl2br(e($card->content)) !!}</p> 13 </div> 14 <div class="d-flex justify-content-between flex-row"> 15 <div class="d-flex flex-row"> 16 @include('good.good_button', ['card' => $card]) 17 </div> 18 </div> 19 </div> 20 </li> 21 @endforeach 22</ul> 23{{ $cards->render('pagination::bootstrap-4') }} 24 25@endsection
good_button.blade.php
php
1@if (Auth::check()) 2 @if (Auth::user()->pressed_good($card->id)) 3 <div class="mr-2"> 4 {{--「良いね」した場合は良いね取り消しボタン--}} 5 {!! Form::open(['route' => ['user.cancel_good', $card->id], 'method' => 'delete']) !!} 6 <button style="cursor:pointer"><i class='fas fa-thumbs-up'></i></button> 7 {!! Form::close() !!} 8 {{--ここに良いねした人のカウントを表示したい--}} 9 </div> 10 11{{--以下省略--}}
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/11 13:58
2019/06/11 21:12