Skip to content
Advertisement

Laravel Relationships with multiple eloquent

Looks like I need some help with the Relationships part.For example, more than one address record of a user is kept in the database.

I can’t view the address part, I think I have a problem with eloquent, but I’m not sure.

Following my code:

user Table

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

1  | Rahuel        | lastnameRahuel
2  | Dalton Miller | lastnameDalton

adress Table

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

UserModel

 public function getAdress()
    {
        return $this->hasMany(Adress::class);
    }

AdressModel

 public function getUser()
    {
        return $this->belongsTo(User::class);
    }

UserController

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

        foreach ($users as $user){
            echo $user->name;
            echo $user->lastname;
            echo $user->adress;
        }

user_migration

public function up()
    {
        Schema::create('user', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('lastname');
        });
    }

adres_migration

Schema::create('adress', function (Blueprint $table) {
     $table->bigInteger('user_id')->unsigned();
     $table->string('adress');
     $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');

        });

Advertisement

Answer

1 User having multiple addresse, so hasMany used and it will return a list of address. so you cant access as $user->adress;

  1. you can loop through $users->getAdress
  2. you can display comma separated address using pluck and join as below.

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

        foreach ($users as $user){
            echo $user->name;
            echo $user->lastname;
            echo $user->getAdress ? $user->getAdress->pluck('adress')->join(',') : '';
        }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement