I have 2 tables 1) users 2) user_companies.
A user belongs to or has one company,
A company has many users.
This is how I determined my relationships.
How can I pull company data for each user?
Attempt to read property "company" on string – is the error I am receiving with my setup.
Here is what I have tried so far and many other combinations but cant seem to figure out how to show the company name which is stored in the user_companies table under the company column. Not sure what I am missing here.
user model
// Relationship between User and Company
public function company()
{
return $this->hasOne(Company::class, 'id','company_id');
//return $this->belongsTo(Company::class, 'company_id');
}
company model
public function user()
{
return $this->hasMany(User::class);
}
userController
public function profile(User $user, Company $company)
{
$company = Users::with(['company']);
//$company = Company::with('user')->find('33');
return view('admin.users.profile', compact('user', 'company'));
}
blade file
{{ $user->company->company }}
migration file (just added new column FK)
Schema::table('users', function (Blueprint $table) {
$table->integer('company_id')->nullable()->unsigned();
$table->foreign('company_id')
->references('id')
->on('user_companies')
->onDelete('cascade');
});
2
Answers
I solved this by doing the following.
user model
user controller
profile blade file
First of all, you should change the relationship of user to company to
belongsTo
:then eager load it by using
with()