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');
});
CodePudding user response:
1 User having multiple addresse, so hasMany used and it will return a list of address. so you cant access as $user->adress;
- you can loop through
$users->getAdress - you can display comma separated address using
pluckandjoinas below.
$users = User::with('getAdress')->get();
foreach ($users as $user){
echo $user->name;
echo $user->lastname;
echo $user->getAdress ? $user->getAdress->pluck('adress')->join(',') : '';
}
CodePudding user response:
Try something like this:
$users = User::with('getLatestAdress')->get();
foreach ($users as $user){
echo $user->name;
echo $user->lastname;
echo $user->getLatestAddress->adress;
}
because you need to call the relation name and then the property.
Update:
Since the relation getAddress returns an array, you could set a new relation to point to the latest one to be displayed.
public function getLatestAdress()
{
return $this->hasOne(Adress::class)->latest();
}
