2

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.

Elaine Marley
  • 2,143
  • 6
  • 50
  • 86

2 Answers2

5

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.

pfrendly
  • 311
  • 2
  • 4
2

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.

Darren Taylor
  • 1,975
  • 14
  • 18
  • This sounds about right but I will use this a lot certainly, how do I change it in the model? right now I have public function team(){return $this->belongsTo('Team', 'team_id');} on Teammember model and hasMany on the Team model – Elaine Marley Aug 03 '14 at 18:11
  • You can create a new method in your Team model and then simply do; `function teamMembersLastName()` `{` `return $this->teammember()->orderBy('last_name')->get()` `}` – Darren Taylor Aug 03 '14 at 19:18