Tales
Tales

Reputation: 1923

Preload relationships in Laravel

I want that every time I instantiate a User in my application from my UsersController, it comes with the relationships that it has created. I mead, for example a User belongsTo a Person and a User hasMany Form. This is the way I handle my object right now:

public function show( User $user ){
    $user->person;
    $user->forms;
    return view( 'admin.show', compact( 'user' ) );
}

But I don't think, that is a correct way to do it. It would be nice if I could get rid of $user->person; and $user->forms;

How can I accomplish it?

Upvotes: 1

Views: 3419

Answers (1)

Shridhar Sharma
Shridhar Sharma

Reputation: 2387

You can do so by using eager loading concept;

public function show( User $user ){
    $user->load(['person','forms']);
    return view( 'admin.show', compact( 'user' ) );
}

Upvotes: 7

Related Questions