0

I am using Eloquent Repository to get a 'menu' by ID, and return all the associated 'menuitems' along with it. This is working fine, but I am having an issue reordering the 'menuitems' by one of their fields. So I am currently doing:

$menu = $this->menuRepo->getById($id, 'menuitems');

which calls this function within the Eloquent Repo:

public function getById($id, $with = false)
{
    if ($with)
    {
        return $this->model->withTrashed()->with($with)->findOrFail($id);
    }

    return $this->model->withTrashed()->findOrFail($id);
}

That function is being used throughout the system, so ideally I want to leave that as it is - or would need to change it so that it would not break in all the current usages. But even so, when I tried to add a

->orderBy('name')

within there it applies to 'menu' and not 'menuitems'.

Quinny
  • 209
  • 4
  • 9
  • 2
    duplicate of [Laravel Eloquent: How to order results of related models?](http://stackoverflow.com/questions/25700529/laravel-eloquent-how-to-order-results-of-related-models#25701143) – Jarek Tkaczyk Sep 30 '14 at 10:02
  • Thanks, I did have a good search first but this question seemed to have slipped the net. – Quinny Oct 01 '14 at 14:47

1 Answers1

0

Your with($with) needs to be rewritten, so that it uses relationship constraints:

...->with($with => function($query){
   $query->orderBy('name','asc');
})->...
Yasen Slavov
  • 787
  • 4
  • 16