Miguel Stevens
Miguel Stevens

Reputation: 9211

Laravel sorting eager loaded data

I'm using the following query to get all companies for a certain event. And they are ordered by name

$companies = Company::where('city_id', 3)->orderBy('name', 'asc')->get();

Now in my view i use eager loading to get all the persons that work for that company

@foreach($companies as $company)
    @foreach($company->persons as $person)
        <tr><td>{{ $person->firstname }}</td></tr>
    @endforeach
@endforeach

I'm trying to sort the persons by name but it's not working. Any idea on how to do this?

Thanks

Upvotes: 0

Views: 156

Answers (1)

Sher Afgan
Sher Afgan

Reputation: 1234

You can further query your relations in Laravel.

For example to get person by names in an ascending order.

@foreach($companies as $company)
    @foreach($company->persons()->orderBy('firstname','asc')->get() as $person)
        <tr><td>{{ $person->firstname }}</td></tr>
    @endforeach
@endforeach

Upvotes: 1

Related Questions