zernzern1993
zernzern1993

Reputation: 265

Filtering eloquent collection with foreign table's attribute

I have a users table and I am trying to return the data to a view after filtering the collection with its foreign table (user_details) by the attribute where "status" = "1".

I have researched and tried many method suggested online such as

$users = Users::whereHas('details_id', function($query) {
    $query->where('status', '1');
})->get()->paginate(15);

But I am getting an error of

Call to undefined method App\Models\User::details_id()

This is my User's model below: -

public function user_details() 
{
    return $this->hasOne(UserDetails::class, "id");
}

Upvotes: 0

Views: 455

Answers (1)

Rwd
Rwd

Reputation: 35190

When using has or whereHas you should use the name of the relationship (the method name) not the field name that relates them:

$users = Users::whereHas('user_details', function($query) {
    $query->where('status','1');
})->paginate(15);

Upvotes: 1

Related Questions