Loading last record of hasMany relationship

Viewed 8272

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.

2 Answers

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

You could achieve this by doing:

in your User model:

/**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['last_phone'];


protected function getLastPhoneAttribute()
{
    return $this->phone()->orderBy('created_at')->first();
}
use App\Model\User;

$lastPhones = User::all()->map->last_phone;
Related