benmacgowan
benmacgowan

Reputation: 185

OrderBy on Eloquent whereHas relationship

I have a simple page which lists counties and there related items under headings. These items need to be approved, hence the whereHas method.

I currently have the following eloquent query;

$counties = County::whereHas('items', function ($query) {
    $query->where('approved', 1);
})->get();

The items returned are currently ordered by their primary field id (it would seem), however I want to list these items alphabetically by their name field.

I have tried the following query, but this does change anything. Any advice would be appreciated?

$counties = County::whereHas('items', function ($query) {
    $query->where('approved', 1)->orderBy('name');
})->get();

Upvotes: 7

Views: 17416

Answers (4)

Nur Uddin
Nur Uddin

Reputation: 1840

$users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');

Upvotes: 0

James Bailey
James Bailey

Reputation: 508

To keep it eloquent, you can put it in the relation, in the Model class:

public function reviews()
{
    return $this->hasMany(Review::class)->orderBy('id','desc');
}

https://laravel.io/forum/09-14-2015-ordering-a-collection-by-the-related-items

Might be late, but hopefully someone stumbles on this (it's the first in google search)

Upvotes: 0

Mathieu Ferre
Mathieu Ferre

Reputation: 4412

when you want to display the result , try this :

@foreach($counties as $county)
    @foreach($county->items->orderBy('name') as $item)
          {{ $item->name }}
    @endforeach
@endforeach

Or in your County Models :

public function approvedItems(){
    return $this->hasMany(Item::class)->where('approved', 1)->orderBy('name');
}

and then :

controller :

$counties = County::whereHas('approvedItems')->get();

view :

@foreach($counties as $county)
    @foreach($county->approvedItems as $item)
          {{ $item->name }}
    @endforeach
@endforeach

Try to work with your models and relationships for having the lightest controller you can, you will gain in lisibility

Upvotes: 0

Sérgio Reis
Sérgio Reis

Reputation: 2523

$counties = County::whereHas('items', function ($query) {
    $query->where('approved', 1);
})->orderBy('name')->get();

I don't think you can order on the subquery, it should be before the ->get

Upvotes: 1

Related Questions