Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get 2 different Models data in one Controller in Laravel 9

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading