Elaine Marley
Elaine Marley

Reputation: 2213

How to sort an Eloquent subquery

I have two tables conected: Team and member. The models are connected by a n:m relationship and in my team views I will make a foreach loop to get the members of said team like this:

@foreach( $team->teammember as $member )
    {{ $member->firstname }} {{ $member->lastname }}
@endforeach

So far everything is great and working, my issue is, how do I get the members list sorted by lastname? In my controller I'm not getting the members, since the connection is done via the model, I can only sort the teams but not the members.

Upvotes: 2

Views: 1575

Answers (2)

pfrendly
pfrendly

Reputation: 321

If you ALWAYS want it sorted by lastname you can also add the sortBy call directly in the relationship function on the model.

    public function teammember() {
    return this->hasMany('Teammember')->orderBy('last_name');
    }

I prefer a separate method in this case as suggested by Darren Taylor to maintain flexibility, but it's nice to know you can chain to the relationship functions directly as well.

Upvotes: 5

Darren Taylor
Darren Taylor

Reputation: 2015

Essentially, you can do this:

@foreach( $team->teammember()->orderBy('last_name')->get() as $member )
    {{ $member->firstname }} {{ $member->lastname }}
@endforeach

However, might be best to abstract this into the Model or something if you plan on doing it alot.

Upvotes: 2

Related Questions