using Larvel 9 and I have Employee and Title Models with relationship one to many. now I need call a function to get all employee and title data using EmployeeController as following.
public function getEmployee() {
return response()->json(Employee::all(), 200);
}
}
my api route is this
Route::get('employees','App\Http\Controllers\EmployeeController@getEmployee');
how could I get title data also in same EmployeeController in same getEmployee function?
>Solution :
If you have a Relationship setup between your Employee and Title Models, you can simply do:
public function getEmployees() {
return response()->json(['employees' => Employee::with('title')->get()], 200);
}
Also, in newer versions of Laravel, the syntax for Routes is as follows:
use App\Http\Controllers\EmployeeController;
Route::get('/employees', [EmployeeController::class, 'getEmployees'])->name('employees');
If you do not have a Relationship setup, or you want both Models separately, you can simply query both models:
public function getEmployees() {
return response()->json([
'employees' => Employee::get(), // or `::all()`
'titles' => Title::get()
], 200);
}
References: