Flex's avatar
Level 4

Call to undefined relationship [title] on model [App\Models\Employee]

working with Laravel 9 and in My App there are Relationship one to many with Employee Model ans Title and Salary. Employee.php

class Employee extends Model
{
    use HasFactory;

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

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

Title.php

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

Salary.php

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

now I am going to get all data using EmployeeController getEmployee function as well EmployeeController.php

use Illuminate\Http\Request;
use App\Models\Employee;
use App\Models\Title;
use App\Models\Salary;


class EmployeeController extends Controller
{
    public function getEmployee() {
        return response()->json(Employee::with('title','salary')->get(), 200);
      
    }
}

and My api.php call is like this

Route::get('employees','App\Http\Controllers\EmployeeController@getEmployee');

but result shown following error message as well

Illuminate\Database\Eloquent\RelationNotFoundException: Call to undefined relationship [title] on model [App\Models\Employee]. in file 

how to fix this?

0 likes
5 replies
khaledw62's avatar

i think there is a typo your relation called title and you access it with title So it'll be like

 return response()->json(Employee::with('titles','salaries')->get(), 200);
Flex's avatar
Level 4

@khaledw62 it is got following error Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'titles.emp_id' in 'where clause' (SQL: sel

Snapey's avatar
Snapey
Best Answer
Level 122

If Title belongsTo Employee then it needs a column linking to employees table.

You have said in your model that it is the emp_no. This should contain the primary key of the Employee

Is that correct?

In your Employee model, you said it was emp_id. Which is it?

Flex's avatar
Level 4

@Snapey yes I got the problem it should be emp_no then it is working but only come Employee Model data not Other Salary and Title Models data as well. my out put like this

[{"emp_no":1,"birth_date":"2014-04-09","first_name":"Amaruki","last_name":"Koshiyama","gender":"male","hire_date":"2023-09-19","created_at":null,"updated_at":null,"titles":[],"salaries":[]}]
Snapey's avatar

@Flex You did not confirm the structure of the titles and salaries tables

Please or to participate in this conversation.