Laravel 4: Eloquent relationship get all data
14,952
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.
Author by
user1995781
Updated on June 18, 2022Comments
-
user1995781 almost 2 years
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.
-
user1995781 about 10 yearsThanks for your answer. But how can i put the memberdetails data into the form? The form only appear data with user table.
-
Gab about 10 years$user->memberdetails->id and so on? Your user has only one memberdetails so you can use it directly.
-
user1995781 about 10 yearsBecause I am working with blade form. Once I pass data it, it automatically populate the data into the form based on form name. So, now only user table is populated into the form.
-
CommandZ over 8 yearsThis doesn't take advantage of Eloquent's eager loading.