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

Info2cell's avatar

Relation of Relation

I need help please. I have three tables

  1. Shop [shop_id, shopname]
  2. Customers[customer_id,shop_id, customername]
  3. Telephones[telephone_id, customer_id, telephone]

I made these relations

#Shops.php
public function Customers() {
        return $this->hasMany('App\Customers');
    }

#Customers.php public function Telephone() { return $this->hasMany('App\Telephones'); } public function Shops() { return $this->belongsToMany('App\Shops'); }

#Telephones.php
public function Customers() { return $this->belongsToMany('App\Customers'); }

#shops
Shop ID  Shop Name
1  Name 01
2  Name 02


#Customers
Customer ID  customername  shop_id
1  John  1
2  Adam  2
3  Steve  1
4  Andy  1

#Telephone
telephone ID  Customer ID  Telephone
1  1  +111111111
2  1  +122222222
3  2  +21111111
4  2  +22222222
5  3  +311111111111
6  3  +32222222222

I want to get all numbers related to shop id 1 $shop->customers->telephone

Error message PHP error: Undefined property: Illuminate\Database\Eloquent\Collection

0 likes
1 reply
bobbybouwmann's avatar
Level 88

Well you have multiple customers, so you need to loop over them to get the phone numbers

$telephones = [];

foreach ($shop->customers as $customer) {
    $telephone [] = $custom->telephone->telephone;
}

// You now have an array of all the telephone numbers

Please or to participate in this conversation.