user1995781
user1995781

Reputation: 19453

Laravel 4: Eloquent relationship get all data

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.

Upvotes: 6

Views: 14989

Answers (2)

Gab
Gab

Reputation: 5784

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.

Upvotes: 21

marcanuy
marcanuy

Reputation: 23942

After getting the user instance, access the relationship, then you can access the other class properties

$user = User::find($id);
$userData = $user->memberdetails;

Upvotes: 0

Related Questions