In my Laravel 8 application, I have the following models.
Company
protected $fillable = [
'id',
'name',
'website',
'company_logo',
'registration_number',
'date_established',
'address',
];
Employee
protected $fillable = [
'id',
'company_id',
'user_id',
'first_name',
'last_name',
'other_name',
'gender',
];
public function company()
{
return $this->belongsTo(Company::class,'company_id','id');
}
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
I started this but got stuck on the way. I want to select company details based on the logged user. The company table should be the main table:
public function getMyCompany()
{
try {
$userId = Auth::user()->id;
$employeeId = Employee::where('user_id', $userId)->first();
$company = Company::...;
return $this->success('Company successfully Retrieved.', [
'company' => $company
]);
} catch (\Exception $e) {
Log::error($e);
return $this->error($e->getMessage(), $e->getCode());
}
}
How do I achieve this (select all details of the company) using:
$company = Company::...;
Making the main model
Use Eloquent Eager loading for this as the Employee
model has a belongsTo
relationship for company
public function getMyCompany()
{
try {
$userId = Auth::user()->id;
$employee = Employee::with('company')->where('user_id',$userId)->first();
$company = $employee->company
return $this->success('Company successfully Retrieved.', [
'company' => $company
]);
} catch(\Exception $e) {
Log::error($e);
return $this->error($e->getMessage(), $e->getCode());
}
}
Refer: https://laravel.com/docs/8.x/eloquent-relationships#eager-loading for how Eager Loading works in Laravel