Search code examples
phplaraveleloquentlaravel-3

How to eager load in Laravel, while finding a specific entry


I want to eagerly load a specific user, with their User Profile. My table and class is called users and User respectively. My Profiles table and class is user_profiles and UserProfile.

This is what I'm trying but it doesn't seem to work

return User::with('user_profiles')->find(1);

Solution

  • You also need to define a relationship method in your User class. Something like:

    public function profile()
    {
       return $this->belongs_to('UserProfile');
    }
    

    You then reference the name of relationship method:

    User::with('profile')->get()