Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(',');
        }

>Solution :

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

echo $user->getAdress->implode('address', ',');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading