Reputation: 15
The following....
Controller:
public function treatmentsList()
{
$treatments = Treatment::with('category')->where('status', 1)->orderBy('medical_name')->get();
$groups = $treatments->groupBy('category.name');
return view('pages.treatments.list', compact( 'groups'));
}
View:
<ul>
@foreach($groups as $category_name => $treatments)
<li>
<h4>{{ $category_name }}</h4>
<ul>
@foreach($treatments as $treatment)
<li>
<h5>{{ $treatment->medical_name }}</h5>
</li>
@endforeach
</ul>
</li>
@endforeach
</ul>
Gives me...
The treatments grouped in their categories and in alphabetical order but the categories are not in alphabetical order.
- Category B
Treatment A
Treatment B
Treatment C
- Category A
Treatment A
Treatment B
- Category C
Treatment A
Treatment B
Treatment C
Treatment D
How can I get the treatments and categories both listed in alphabetical order?
Upvotes: 1
Views: 108
Reputation: 9988
You can get this by adding query constraints for the eager loading query:
Treatment::with(['category' => function ($query) {
$query->orderBy('name');
}])
->where('status', 1)
->orderBy('medical_name')
->get();
Hi,
I'm not sure if this is what you mean... but it did not worked... I still get the categories not alphabetically listed.
public function treatmentsList()
{
$treatments = Treatment::with(['category' => function ($query) {
$query->orderBy('name');
}])
->where('status', 1)
->orderBy('medical_name')
->get();
$groups = $treatments->groupBy('category.name');
return view('pages.treatments.listA', compact( 'groups'));
}
You're right - my mistake. I think that answer is the join query:
public function treatmentsList()
{
$treatments = Treatment::with('category')
->select('treatment.*')
->join('category', 'category.id', '=', 'treatment.category_id')
->where('treatment.status', 1)
->orderBy('category.name')
->orderBy('treatment.medical_name')
->get();
$groups = $treatments->groupBy('category.name');
return view('pages.treatments.listA', compact( 'groups'));
}
Check the names of tables and fields from above example. This should work.
Upvotes: 1