laraveleloquentlaravel-6

Loading last record of hasMany relationship


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.


Solution

  • 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();