'Laravel - How to get company detail based on employee and logged user

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



Solution 1:[1]

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

Solution 2:[2]

I'm not sure if you're expecting to get multiple companies from the user, or just a single one. The reason I'm not sure is that you have defined a 1-1 relationship between a company and an employee, yet it looks like you want getMyCompany() to return multiple companies.

If the idea is to retrieve only the one company that the employee works at, you can use the employee's "belongsTo"-relationship as following:

$company = $employee->company;

Since you have already retrieved the employee related to the authenticated user, and the employee model has a "company"-relationship.

If you want to do it in one go, you can chain the queries:

$company = Employee::where('user_id', Auth::user()->id)
                     ->first()
                     ->company;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abishek
Solution 2 Megadöden