3

I have 2 tables employees and employee_locations. One employee has many locations. I need to find out one employee record with related latest employee_locations record. I wrote below query.

$employees = Employee::find([1])->with('employees.employee_locations')->latest()->first();

I am getting below error

BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::with does not exist.
abu abu
  • 6,599
  • 19
  • 74
  • 131

3 Answers3

3

Your issue is that the find method retrieves a collection of Eloquent objects, on which the with method can not be used. You must first specify your relations for the Employee objects and then use find.

The below code will retrieve the employee with the ids specified in find method and locations for each employee:

$employees = Employee::with('employees.employee_locations')->find([1])
arm
  • 145
  • 1
  • 5
  • I am getting `Call to undefined relationship [employees] on model [App\Employee]. ` error. – abu abu Dec 04 '19 at 11:07
  • 1
    It means your relationship is not defined properly in the Employee model. Can you show us your Employee model? – arm Dec 04 '19 at 11:18
  • Thanks @arm. Here is Employee model `hasMany(Employee_location::class); } }` – abu abu Dec 04 '19 at 11:44
  • 1
    since your relationship method is called employee_locations you should use that inside the with function like this: with('employee_locations') – arm Dec 04 '19 at 11:46
1

create a relation in your model. Something like this:

class Employee extends Model
{

    protected $table = 'employees';

    public function location()
    {
        return $this->hasMany(EmployeeLocation::class, 'employeed_id');
    }
}

class EmployeeLocation extends Model
{
    protected $table = 'employee_locations';
}

$employees = Employee::with('location')->first();
or you do
$employees = Employee::with('location')->find(<employeed_id>);
0

Try This method

$employees = Employee::with('employees')->where('employeesid',$employeesid)- 
>get()->find($employeesid);
Rahul Kr Daman
  • 387
  • 3
  • 15
  • 1
    Thanks @Bloody. I am getting `Call to undefined relationship [employees] on model [App\Employee]. ` error. – abu abu Dec 04 '19 at 11:07