Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent - equivalent to first() for last?

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??

like image 844
StackOverflowed Avatar asked Aug 17 '14 19:08

StackOverflowed


People also ask

What is latest () in Laravel?

->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.

What does First () return in Laravel?

It just returns null.

What is first () in eloquent?

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.

How can I get last record in Laravel?

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.


1 Answers

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();
like image 174
Jarek Tkaczyk Avatar answered Oct 03 '22 02:10

Jarek Tkaczyk