I have employees list in my database table:
Table: Employees
Employee model code:
public function workplace()
{
return $this->morphTo();
}
Company model code:
public function workers()
{
return $this->morphMany('App\Employee', 'company');
}
Branch model code:
public function workers()
{
return $this->morphMany('App\Employee', 'company');
}
Now I get user worklaces in sample different form:
$userWorkplaces = Employee::where('user_id', Auth::id())->get();
$workplace_info = [];
foreach ($userWorkplaces as $workplace) {
if($workplace->company_type == "App\Company") {
$company = Company::findOrFail($workplace->company_id);
$type = 'Company';
} elseif($workplace->company_type == "App\Branch") {
$company = Branch::findOrFail($workplace->company_id);
$type = 'Branch';
}
$workplace_info[] = [
'company' => $company->name,
'type' => $type
];
}
dump($workplace_info);
Result:
array:3 [
0 => array:2 [
"company" => "Mahorat"
"type" => "Company"
]
1 => array:2 [
"company" => "Babolo"
"type" => "Company"
]
2 => array:2 [
"company" => "Филиал Махорат"
"type" => "Branch"
]
]
How I can get easyly sample result by creating laravel relationships in models?
You have to change in your Employee
relationship function name company
because you have company_id
and company_type
fields in employee table
Employee model code:
public function company()
{
return $this->morphTo();
}
Now fetch data
$employees = Employee::where('user_id', Auth::id())->get();
$workplace_info = [];
foreach($employees as $employee){
$workplace_info[]['company'] = $employee->company;
$workplace_info[]['type'] = get_class($employee->company);
}
dd($workplace_info);
Details https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations