skip to Main Content

I have 3 Models in My Laravel App like Employee , Salary and Title. Employee Model one to Many Relationship with both Salary and Title Models. Now I need get all data using EmployeeController getEmployee function

EmployeeController

public function getEmployee() {
        return response()->json(Employee::with('titles','salaries')->get(), 200);
      
    }

and my api route is following

Route::get('employees','AppHttpControllersEmployeeController@getEmployee');

but when I try get above data I could get only Employee Model data like this
[{"emp_no":1,"birth_date":"2014-04-09","first_name":"Marukoi","last_name":"Ashikawa","gender":"male","hire_date":"2023-09-19","created_at":null,"updated_at":null,"titles":[],"salaries":[]}]

titles and salaries table data not retrieve and empty array.how could I fix this matter?


Employee Model

 public function titles(): HasMany
    {
        return $this->hasMany(Title::class, 'emp_no');
    }

    public function salaries(): HasMany
    {
        return $this->hasMany(Salary::class, 'emp_no');
    }
}

Salary Model

 public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class, 'emp_no');
    }

Title Model

public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class, 'emp_no');
    }

2

Answers


  1. I think everything looks good but the issue is your custom foreign and primary key. Try something like

        public function titles(): HasMany
        {
            return $this->hasMany(Title::class, 'emp_no', 'emp_no');
        }
    
        public function salaries(): HasMany
        {
            return $this->hasMany(Salary::class, 'emp_no', 'emp_no');
        }
    

    Please check the following documentation from Laravel

    return $this->hasMany(Comment::class, 'foreign_key');
     
    return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
    
    Login or Signup to reply.
  2. Please use array inside "with". public function getEmployee() { return response()->json(Employee::with(['titles','salaries'])->get(), 200); }.
    It should work for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search