For sorting on a relation you have no other choices than joining the table.
Sorting tables with relations
Hi guys,
I was wondering how to sort my tables that contain the information of let's say locations. Now each location is connected to a client. Of course I have the relations set up.
Now what I have is that when you click on the <th> it will sort the table by that column by adding the parameters to the url. So my url looks like this when I click on '
http://project.app/locations?sortBy=address&direction=asc&page=1
Now the problem when I need to sort on for example the client name. Using the relation I can show the name of client using $location->client->name because I eager load the client as well. But when I want to sort on the client I get this url
http://project.app/locations?sortBy=client_id&direction=asc&page=1
Now for the sorting part I added a scope to my model for each sorting that I can call with this query
return Location::with('client')->sortable($request)->paginate(10);
And here is the scope function
public function scopeSortable($query, Request $request)
{
if ($request->get('sortBy') && $request->get('direction'))
return $query->orderBy($request->get('sortBy'), $request->get('direction'));
return $query;
}
As you can see this will only work for columns in the model and not for relations. So my question is how can I make this work with relations as well! The scope is now sorting on the client_id instead of the client name..
If you need more information please let me know
All help is welcome ;)
Please or to participate in this conversation.