Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rafe's avatar
Level 1

How to get filterd results in eloquent relation with

This is my Customer model

class Customer extends Model
{
    use SoftDeletes;
    protected $fillable  = ['name','place','address','provider','userid','senderid','pin','route','voicekey','burl','amc','amc_date','voice','active'];
    protected $dates = ['deleted_at','created_at','updated_at','amc_date'];

    public function User()
    {
        return $this->hasMany('SmSPortal\User');
    }    

    public function Student()
    {
        return $this->hasManyThrough('SmSPortal\Student','SmSPortal\User');
    }
}

and this is my code

$data = Customer::whereId(2)->with('User.Student')->get();

now i want iterate through each users to get students

return $data[0]->User[0]->Student[0]->name

but i only need all the students

pls help me

0 likes
2 replies
pmall's avatar
pmall
Best Answer
Level 56

Use WhereHas :

$students = Student::whereHas('user.customer', function ($query) use ($customer_id) {

    $query->where('id', '=', $customer_id);

})->get();

It assumes Student has a belongsTo relationship with User named user and User has a belongsTo relationship with Customer named customer.

Also you should follow conventions for naming your relationships : lowercase name, singularized for belongsTo or hasOne, pluralized for *Many relationships.

Rafe's avatar
Level 1

thank u pmall its working

Please or to participate in this conversation.