Skip to content
Advertisement

Eloquent Relationships hasMany use loop

I have a database with multiple address records of a user. When I do “pluck()” and “join()” in the foreach path, I get results. But when I type $user->getAddress->address in structures like hasOne, I get the result I want. In short, can I return the loop in hasMany more practically?

Following my code:

user Table

id |    name       | lastname |
--- --------------  ----------   

1  | Rahuel        | lastnameRahuel
2  | Dalton Miller | lastnameDalton

adress Table

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

UserModel

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

Controller

$users = User::with('getAddress')->get();

        foreach ($users as $user){
            echo $user->name;
            echo $user->lastname;
            echo $user->getAdress->pluck('address')->join(',');
        }

Advertisement

Answer

You can use the Collection ‘s implode method to make it look a bit less verbose.

echo $user->getAdress->implode('address', ',');
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement