Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 536
user1995781 Avatar asked Feb 25 '14 01:02

user1995781


1 Answers

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.

like image 169
Gab Avatar answered Oct 23 '22 12:10

Gab