Rizki Hadiaturrasyid
Rizki Hadiaturrasyid

Reputation: 448

Laravel Eloquent retrieving data with 'with' and finding based on values in this 'with'

So I have a Players table and Loans table.

Players
id | name | age

Loans
id | player_id (foreign key) | status

I can get all players and their loans by using this:

Player::with('loans')->paginate(15);

Now I want to list all players where the loans status is certain value, how do I do that?

Something like:

Player::with('loans')->where('loans.status',$status)->paginate(15);

Upvotes: 0

Views: 29

Answers (1)

lagbox
lagbox

Reputation: 50481

You are looking for whereHas for this:

Player::whereHas('loans', function ($q) use ($status) {
    $q->where('status', $status);
})->paginate(15);

This is querying based on the existence of a relationship.

Laravel 5.6 Docs - Eloquent - Relationships - Querying Relationship Existence

Upvotes: 1

Related Questions