luk luk - 1 year ago 135
PHP Question

laravel 4.2 eloquent: get all() + related column

Let's say we have 2 models, with following relations:


public function BookCode() {
return $this->hasOne( 'BookCode' );


public function User() {
return $this->belongsTo( 'User' );

Now we'd like to get all records from User with book_code from BookCode (empty if none) as an array. Is something like that possible? The only thing I came up, which seems to be very slow (takes 30 secs to execute), was:

$users = User::all();

foreach( $users as $user ) {
$users_array[] = array(

// this is very slow

Would it be possible to get an array of Users with related book_codes "in one go"? Couldn't find any solution to this for 5 hrs now.

Answer Source

Set the relationships that should be eager loaded.

$users = User::with('BookCode')->get();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download