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);
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?
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?
Please or to participate in this conversation.