Reputation: 9495
I have a Sites
model which hasMany Posts
.
I would like to know whats the most efficient eloquent query to return all Site records along with the 1 (most recent) Post record.
I have tried using this in my Sites modal but it returns all Posts which is not what I want.
public function lastPost()
{
return $this->hasMany('App\Post')->last();
}
Another issue I am having is trying to print a single column in my view.
{{ $site->lastPack->name }}
returns
$name undefined property
... despite this being a valid column in my Post model.
Upvotes: 1
Views: 905
Reputation: 5324
Change Your lastPost
relationship to hasOne
like so:
public function lastPost()
{
return $this->hasOne('App\Post')->latest('id');
}
Upvotes: 1