Home > Net >  Laravel relationship HasMany
Laravel relationship HasMany

Time:05-07

I keep multiple address records belonging to a user. but when i write with dd i can't access other table's data.

Following my code:

user Table

id |    name       | country |
--- --------------  ----------   

7  | Mr. Lenny Bins| Belgium
2  | Dalton Miller | Swaziland

address Table

user_id | address         
-------- ---------
7       | 740 Brown Greens Suite  
7       | 9906 Cleora Wall Apt.      
2       | 53977 Kip Center Apt

UserModel

 public function getAddress()
    {
        return $this->hasMany(Address::class);
    }

UserController

$users = User::where('id' ,7)->with('getAddress')->get();

dd($users->toArray());
// The output of this is below

The output of this

dd($users->getAddress->toArray());

I get an error when I try like this.

Property [getAddress] does not exist on this collection instance.

CodePudding user response:

Firstly you are using get that will return collection, In Following you will get all users with their addresses.

$users = User::where('id' ,7)->with('getAddress')->get();

You can use first() instead of get() as you are finding only one user

$user = User::where('id' ,7)->with('getAddress')->first();

If You want only address of that user use

dd($user->getAddress)

Or If you want only in form of array use

dd($user->getAddress->toArray())

Give an Upvote if you get it.

CodePudding user response:

User Model

public function getAddress()
{
  return $this->hasMany('App\Address');
}

Get User(s)

$users = \App\User::with('getAddress')->where('id' ,7)->get();

Iterate and read data

foreach ($users as $user) {
  echo '<pre>' , var_dump($user->getAddress()->first()['address']) , '</pre>';
}

CodePudding user response:

$users = User::with('getAddress')->where('id' ,7)->get();

dd($users);

  • Related