When I echo this:
<?php echo $photo->votesCount ?>
I get
[{"photo_id":1,"votes":2}]
How do I display the votes (2)?
Here's a vardump of the object: http://pastebin.com/ddAkRk4c
If I type:
<?php print_r( $photo->votesCount )?>
I get this: http://pastebin.com/ZfE76WmB
The complete view:
2 @foreach($photos as $photo)
3 <li class='photo'>
4 <img src="{{URL::to('/')}}/uploads/{{$photo->name}}" width="150">
5 <div>
6 <a href="{{route('photos.show',$photo->id)}}">{{ $photo->name }}</a>
7 <?php $photo_array = json_decode($photo);
8 echo $photo_array->votes; ?>
9 </div>
10 </li>
11 @endforeach
Part of the Controller logic:
$photos = Photo::where('period_id', $currentPeriod)
->with('votesCount')
->get();
return view('home', ['uploaded' => $uploaded, 'photos' => $photos, 'period' => $currentPeriod]);
Model:
public function votes()
{
return $this->hasMany('App\Vote');
}
public function votesCount()
{
return $this->votes()
->selectRaw('photo_id, count(*) as votes')
->groupBy('photo_id');
}