Reputation: 1993
I have the following controller and models:
Appointments Controller:
if ($view === 'default') {
$appointments = Appointment::with('label')->with('status')->paginate(25);
}
if ($view === 'label') {
$appointments = Label::with('appointments')->paginate(25);
}
Appointment Model:
public function label()
{
return $this->belongsTo('App\Label');
}
Label Model:
public function appointments()
{
return $this->hasMany('App\Appointment');
}
In my "default" view, the following is displayed:
And in my "label" view, the following is displayed:
What I want to accomplish is, when a label has no appointments, I do not want the label to be shown at all. So, in my "label view" (check out the below image) I only want the "business" and "personal" label (and it's appointments as shown in image) to be displayed, and all the other labels shouldn't be displayed.
In my views I am using simply foreach loops. Any pointers in the right direction?
My view (simple):
@if ($view === 'label')
@foreach ($appointments as $appointment)
<table>
<tr>
<th><p>{{ $appointment->label }}</p></th>
</tr>
@foreach ($appointment->appointments as $label)
<tr>
<td>{{ $label->appointment }}</td>
</tr>
@endforeach
</table>
@foreach ($appointments as $appointment)
@endif
Upvotes: 1
Views: 405
Reputation: 1041
Try this:
You can achieve this by checking for non empty appointments. Here we would check for the negative case of empty () method.
View (blade)
@if ($view === 'label')
@foreach ($appointments as $appointment)
<table>
@foreach ($appointment->appointments as $key=> $label)
@if(!empty($label))
@($key == 0)
<tr>
<th><p>{{ $appointment->label }}</p> </th>
</tr>
@endif
<tr>
<td>{{ $label->appointment }}</td>
</tr>
@endif
@endforeach
</table>
@endforeach
@endif
Hope this is helpful.
Upvotes: 1
Reputation: 7447
You need to check the length of the array before you write the label. So here you'd make sure that $appointment->appointments count is greater than 0.
@if ($view === 'label')
@foreach ($appointments as $appointment)
@if (count($appointment->appointments) > 0)
<table>
<tr>
<th><p>{{ $appointment->label }}</p></th>
</tr>
@foreach ($appointment->appointments as $label)
<tr>
<td>{{ $label->appointment }}</td>
</tr>
@endforeach
</table>
@endif
@foreach ($appointments as $appointment)
@endif
Upvotes: 1