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.
User::all() will return a collection of User s, hence you have to use a loop to retrieve each user's address...
actually I need a collection of addresses like below:
$address = $user->address->where('country','UK');
Hello,
You can try this.
$adresses = User::all()->where('country', 'UK')->pluck('address');
Tell me if it works. ;)
Column not found: 1054 Unknown column 'country' in 'where clause' (SQL: select * from users where country = 0)
@vincent15000
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 ?
Yes! One user have only one address.
addressTable=['id','user_id','country','zip',.....]
@vincent15000
Tell me the fields you want to retrive in your collection.
Why not just query the Address model directly?
@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();
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
@golapraj And you can replace join() by leftJoin() or rightJoin() according to your need to discard the users without any address.
DB::table('addresses')
->leftJoin('users', 'users.id', '=', 'addresses.user_id')
->select('users.name', 'addresses.address')
->where('addresses.country', 'UK')
->get();
@golapraj Tell us if it's ok for you please ;).
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();
Good idea @snapey , I didn't know that way.
@golapraj With pleasure. Perhaps you could click for the best answer in order to close this post ?
Please sign in or create an account to participate in this conversation.