omrakhur omrakhur - 1 year ago 70
PHP Question

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

I have a

model, in which I have the following function:

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

Then there is an
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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download