I have a typical model relation. I have the model QR
, which hasMany
Rating, and a Model Rating
, which belongsTo Qr
.
Now I want to output the Ratings
, which belong to a single qr
model, through a foreach
loop like this:
<table>
<tr>
<th>ID</th>
<th>UnitID</th>
<th># of Ratings</th>
</tr>
@foreach($qrs as $qr->ratings)
<tr>
<td>{{$qr->id}}</td>
<td>{{$qr->unit_id}}</td>
<td>{{$qr->ratings->count()}}</td>
</tr>
@endforeach
</table>
This is my Controller:
public function index()
{
//
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
return View::make('index')
->with('unit', $unit)
->with('qrs', $qrs);
}
Here are my two Models
Rating.php:
class Rating extends \Eloquent {
protected $guarded = [];
public function qr(){
return $this->belongsTo('Qr');
}
}
Qr.php:
class Qr extends \Eloquent {
protected $guarded = [];
public function unit(){
return $this->belongsTo('Unit');
}
public function ratings(){
return $this->hasMany('Rating');
}
}
I actually want to output the count of ratings
, a Qr-Code has. I know it is possible to do it somehow like this:
{{Rating::where('qr_id', $qr->id)->count()}}
But I want to do it somehow like this in the foreach
loop
{{ $Qr->rating->count() }}
If this is somehow possible.
I get the relation, if I just output the first()
of Qr
and then var_dump($qrs->ratings->toArray())
But I don't know how to get the count Number of ratings in combination with the foreach
loop. Any help would be dearly appreciated.
Couple of things wrong here:
// view:
@foreach($qrs as $qr->rating)
// should be:
@foreach($qrs as $qr)
// controller:
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
// this way you get all Units then fetch first Unit from the collection,
// the same with Qrs, so change it to:
$unit = Unit::all(); // do you need it at all?
$qrs = Qr::with('ratings')->get();
This will solve the problem and in the foreach loop you will be able to access $qr->ratings->count() which will be Collection method.
At first you have used this:
@foreach($qrs as $qr->ratings)
You need to change it to this (as already stated in an answer):
@foreach($qrs as $qr)
Then in your index
method you have used this:
public function index()
{
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
return View::make('index')->with('unit', $unit)->with('qrs', $qrs);
}
In this case you need to get a collection of QR
models and since Unit
and Rating
are related to Qr
then you may use with
and get()
to get a collection of QR
models like this:
public function index()
{
$qrs = Qr::with(array('unit', 'ratings'))->get();
return View::make('index')->with('qrs', $qrs);
}
Then you'll be able to loop the Qr
models in your view
like this:
@foreach($qrs as $qr)
<tr>
<td>{{ $qr->id }}</td>
<td>{{ $qr->unit_id }}</td>
<td>{{ $qr->ratings->count() }}</td>
</tr>
@endforeach