I have Angular App connected with Laravel API. In Laravel API there are one to many relationship between Employee and Salary Models.
Employee.php
protected $fillable = ['birth_date','first_name','last_name','gender','hire_date'];
protected $primaryKey = 'emp_no';
public function salaries(): HasMany
{
return $this->hasMany(Salary::class, 'emp_no','emp_no');
}
and Salary.php
protected $fillable = ['salary','from_date','to_date'];
public function employee(): BelongsTo
{
return $this->belongsTo(Employee::class, 'emp_no');
}
now I need print Salary Model data on Angular app. so, I try in this way
<div class="basic-info">
<p>Employee Name : {{employee.first_name}}</p>
<p>Date of Birth :</p>
<p>Gender :</p>
<p>Hire Date :</p>
</div>
<div class="salary-topic">
<h4><b>Salary Details</b></h4>
</div>
<div class="salary-details">
<table class="table">
<thead>
<tr>
<th scope="col">salary {{employee.salary}}</th>
<th scope="col">From Date{{employee.from_date}}</th>
<th scope="col">To Date{{employee.to_date}}</th>
</tr>
</thead>
</table>
</div>
my data.service.ts is like this
getEmployeeById(id: string){
return this.httpClient.get('http://127.0.0.1:8000/api/employee/'+id);
}
and employee-by-id.ts is
getData() {
this.dataService.getEmployeeById(this.id).subscribe(res => {
// console.log(res);
this.data = res;
this.employee = this.data;
})
}
Laravel Controller for get Employee by id
public function getEmployeeById($id) {
$employee = Employee::with('titles','salaries')->find($id);
if(is_null($employee)) {
return response()->json(['message' => 'Employee Not Found'], 404);
}
return response()->json($employee::with('titles','salaries')->find($id), 200);
}
api route
//get specific employee
Route::get('employee/{id}','AppHttpControllersEmployeeController@getEmployeeById');
my Employee model data is printing well. but relathionship Salary Model is not printing. in browser element printing both model data well in json format. how could I fix this problem?
json output
Layout was forced before the page was fully loaded. If stylesheets are not yet loaded this may cause a flash of unstyled content. node.js:383
Angular is running in development mode. vendor.js:47622:13
XHRGET
http://127.0.0.1:8000/api/employee/1
[HTTP/1.1 200 OK 228ms]
emp_no 1
birth_date "1983-10-05"
first_name "David"
last_name "Koner"
gender "male"
hire_date "2023-09-18"
created_at null
updated_at null
salaries [ {…} ]
0 Object { emp_no: 1, salary: 27000, from_date: "2023-09-22", … }
emp_no 1
salary 27000
from_date "2023-09-22"
to_date "2023-09-19"
created_at "2023-10-09T08:17:26.000000Z"
updated_at "2023-10-09T08:48:02.000000Z"