0
votes

I'm new at Laravel and I want some help with a Query. Here is my situation. I have 4 tables:

  • users (id, email, password.....)
  • user_profile (id, first_name, last_name,........, user_id)
  • companies (id, name,.......)
  • policies (id, policy_num, exp_date,........., user_id, company_id)

The table user have 5 users and every user have 10 policies. The table company have 3 companies.

$user_data=User::select('*')
                ->with('profile','policies')
                ->where('id', '=', $userId)
                ->first();

This code is working good, it retrieves the all the users and user_profile fields and all the policies(10) of this user with as you can see in this image, and I can show the user the details of the products on a home page.

Click here to view the image

I want to instead of appear the company_id from the policies table appears the name of the company from the company table. Any help is appreciated.

1
Set up relationships between the models.ceejayoz
Then you'd do something like $user->company->name, using the relationships.ceejayoz
Thanks for your help, i have to add the company table in the query and looks like : $user_data=User::select('*')->with('profile','policies', 'company')->where('id', '=', $userId)->first(); But when i do this i get this error: Call to undefined method Illuminate\Database\Query\Builder::company()Carlos
If i dont put the company table in the query i get this error: Trying to get property of non-objectCarlos

1 Answers

0
votes

Thank you for your answer ceejayoz, i already did.

User

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

public function policies()
    {
        return $this->hasMany('Policy');
    }

Policy

public function company()
    {
        return $this->hasOne('Company');
    }