How to make that query with eloquent
SELECT employees.first_name, companies.name FROM employees JOIN companies ON employees.company_id = companies.id
My relationships
public function employees() { return $this->hasMany(Employee::class); } public function company() { return $this->belongsTo(Company::class); }
I fetching the name with a given ID, but how can I find it for all. Or maybe I am thinking wrong
$employee = $employee->all()->find($id)->company->name;
Advertisement
Answer
I assumed your employees
Model name as Employee
and companies
Model name as Company
$employees = Employee::with('company')->get(); if(!empty($employees)){ foreach($employees as $employee){ echo $employee->first_name; echo $employee->company->name; } }
If you want to search per id then you may do as below.
$employee = Employee::with('company')->find($id); echo $employee->company->name;