omrakhur omrakhur - 3 months ago 14
PHP Question

How do I properly query a one-to-one rel in my Eloquent models?

I have a

User
model, in which I have the following function:

public function employees()
{
return $this->hasOne('App\Employee','userid');
}


Then there is an
Employee
model, which has a function:

public function users()
{
return $this->belongsTo('App\User','userid');
}


Now I want to implement this functionality, can I do this:

$user = User::findOrFail($user->id);
$employee = $user->employees()->where('userid',$user->id)->get();
$employeeStartDate = $employee->startdate;

Answer

Since you're working with one to one relationships, it'd be easier to understand your relationships if you renamed them to their singular versions (employee(), user()).

Then, you can load the relationship in your query using the with() method:

public function index()
{
    $user = User::with('employee')->findOrFail($id);

    $startDate = $user->employee->startdate;
}