0

I have an Project table which belongsTo a Client what I want to achieve is ordering the Project table by Clients name, how do I call the name of the client to the orderBy of the Project query?

        $projects = Project::where('company_id', Auth::user()->company_id)
        ->search(trim($this->search))
        ->orderBy($this->column, $this->order)
        ->paginate($this->size);
kgcusi
  • 215
  • 7
  • 18
  • Take a look at the upvoted (not accepted) answer here: [How to order by another table join by eager loading in Laravel](https://stackoverflow.com/questions/20215967/how-to-order-by-another-table-join-by-eager-loading-in-laravel) Seems like you would need to join and simply reference that table.column on the orderBy. – ficuscr Feb 23 '22 at 01:42

1 Answers1

0

You could do it with a subquery:

$projects = Project::where('company_id', Auth::user()->company_id)
    ->search(trim($this->search))
    ->orderBy(
        Client::select('name')
            ->whereColumn('id', 'projects.client_id')
            ->limit(1)
    )
    ->paginate($this->size);

If you also need the orderBy field to be conditional, you can wrap it in a when().

You can read more about Eloquent subqueries here: https://laravel-news.com/eloquent-subquery-enhancements

P. K. Tharindu
  • 2,565
  • 3
  • 17
  • 34