I want to order my categories by the first result of my with clause.
For exemple there is 3 categories and each categories contains prestations :
If my search query is Cars I want my collection return :
But I don't know how to do that, can someone help me ?
I can't explain better...
Thank you !
$search = $request->search ?? '';
$categories = Category::with(['prestations' => function($query) use($search){
$query->where('prestation', 'LIKE', '%' . $search . '%');
}])
//order by the categories with first result ?
->get();
Eloquent relationships are retrieved using a separate query which happens after the query to retrieve the main model so it is not possible to order the main query results based on values obtained in the relationship query. In your particular use case you can however sort after retrieving the results:
$search = $request->search ?? '';
$categories = Category::with(['prestations' => function($query) use($search){
$query->where('prestation', 'LIKE', '%' . $search . '%');
}])
->get()
->sortBy(function (Category $category) {
return $category->prestations->count(); // Or any other sort criteria you want
});