I have 2 relationship data table; users table and memberdetails table.
Users.php
class Users extends Eloquent{
public function memberdetails()
{
return $this->hasOne('Memberdetails','user_id');
}
}
Memberdetails.php
class Memberdetails extends Eloquent{
public function user()
{
return $this->belongsTo('Users','user_id');
}
}
When I try to retrieve data, with $data = User::find($id);
I only get data from users table.
Example of my blade form:
{{-- User's Name, stored on user table --}}
{{ Form::text('name',null, array('id'=>'name','class'=>'form-control','required')) }}
{{-- User's address, stored on member table --}}
{{ Form::text('address',null, array('id'=>'address','class'=>'form-control','required')) }}
When I visit, localhost/user/2/edit/
, the name field is populated, but address field is empty. How can I retrieve data from both tables and put into a form for editing?
Thank you.
You could use eager loading.
$user = User::with('memberdetails')->find($id);
Using this, you will automatically get the memberdetails when retrieving the user. Then you can use $user->memberdetails
Using eager loading, you do only one query to the DB so it should be the preferred way. If you dont use the with('memberdetails')
, you will perform a second query when accessing the memberdetails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With