I have a few models such as User, Post, Comment, etc.
In the User, I have:
public function posts()
{
return $this->hasMany('Post');
}
I can get the first post via $customer->posts()->first()
, but what if I want to get the latest Post? There is no last() as I can see.
This is further compounded by a hasManyThrough relationship (unfortunately we inherited a wacky schema):
public function comments()
{
return $this->hasManyThrough('Comment', 'Post');
}
If I try to do an $this->comments()->orderBy('comments.id', 'desc')->first();
it returns a User object??
->latest() fetches the most recent set of data from the Database. In short, it sorts the data fetched, using the 'created_at' column to chronologically order the data.
It just returns null.
The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.
Use Model::where('user_id', $user_id)->latest()->get()->first(); it will return only one record, if not find, it will return null . Hope this will help.
No, this
// User model
$this->comments()->orderBy('comments.id', 'desc')->first();
won't return User
model.
And to get what you asked for, simply do this:
$customer->posts()->latest()->first();
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