I have the following code in my controller where I am trying to load all 'members'. Every member can have more than one phone number. Phone numbers are stored in a table called phone_numbers
and are tied to user id's. Below, I am trying to load the last phone number stored for every member. Note, the user has a hasMany relationship on the phone.
User.php
public function phone()
{
return $this->hasMany('App\Model\PhoneNumber');
}
This is what I tried:
$members = \App\Model\User::all();
$members->load('phone');
I appreciate any suggestions on how to accomplish this.
To get the latest row, you can just use latest
, and use hasOne
relationship like this:
public function phone()
{
return $this->hasOne('App\Model\PhoneNumber')->latest();
}
So you can get the latest phone for all users:
User::with('phone')->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With