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

golapraj's avatar

How to retrieve address of all User

//User Model
public function address()
{
        return $this->hasOne('App\Address');
 }

//Address Model
public function user()
{
      return $this->belongsTo('App\User');
}

// I want 
$user=User::all();
$address = $user->address;

error: Property [address] does not exist on this collection instance.
0 likes
20 replies
siangboon's avatar

User::all() will return a collection of Users, hence you have to use a loop to retrieve each user's address...

golapraj's avatar

actually I need a collection of addresses like below:

$address = $user->address->where('country','UK');
vincent15000's avatar

Hello,

You can try this.

$adresses = User::all()->where('country', 'UK')->pluck('address');

Tell me if it works. ;)

golapraj's avatar

Column not found: 1054 Unknown column 'country' in 'where clause' (SQL: select * from users where country = 0)

@vincent15000

vincent15000's avatar

Oh sorry I thought the address was a field of your user table. I just noted that you have a specific table for the addresses.

You have only one address for each user ?

What are the fields in your address table in the database ?

Do you want only the addresses in your collection ?

$addresses = Address::all()->where('country', 'UK')->pluck('address');

Or do you want the addresses with the associated user ?

golapraj's avatar

Yes! One user have only one address. addressTable=['id','user_id','country','zip',.....] @vincent15000

vincent15000's avatar

Tell me the fields you want to retrive in your collection.

Snapey's avatar

Why not just query the Address model directly?

vincent15000's avatar

@snapey Yes I thought about this solution, but I wonder he wants to retrieve the user name too. Perhaps the solution is with DB::table().

You can try something like this.

DB::table('users)->join('addresses', 'users.id', '=', 'addresses.user_id')->select('user.name', 'addresses.address')->where('addresses.country', 'UK')->get();
golapraj's avatar

I need the users & addresses (if that user has a address exist in the address table) I want to discard those users who has no address @snapey @vincent15000

vincent15000's avatar

@golapraj And you can replace join() by leftJoin() or rightJoin() according to your need to discard the users without any address.

vincent15000's avatar
DB::table('addresses')
	->leftJoin('users', 'users.id', '=', 'addresses.user_id')
	->select('users.name', 'addresses.address')
	->where('addresses.country', 'UK')
	->get();
Snapey's avatar
Snapey
Best Answer
Level 122

You could use whereDoesntHave if you want models that are missing a relation.

You can query using whereHas if you want models that have a particular type of child relation


User::with('address')->whereHas('address',function($query){
	$query->where('country','UK');
})->get();
1 like

Please or to participate in this conversation.