yehuda4e
yehuda4e

Reputation: 1

Laravel sorting last record

I'm bulding a forum.

In the main page, I want to show the last reply for each forum.

The hierarchy is this:

forums

hasMany('App\Topic')

hasManyThrough('App\Topic', 'App\Repley')

topics

belongsTo('App\Forum')

hasMany('App\Reply')

replies

belongsTo('App\Topic')

I did this:

 $forum->replies()->orderBy('created_at', 'desc')->first()

And it worked. But I want to sort by topics and replies. If I post new topic after the last reply, I want that show as the last reply.

Update: I did this, and it work. But is there any other way?

public function last() {
    $topic = $this->topics->sortByDesc('created_at')->first();
    $post = $this->replies->sortByDesc('created_at')->first();

    return ($topic->created_at > $post->created_at) ? $topic : $post;
}

Upvotes: 0

Views: 814

Answers (5)

Hamza Dairywala
Hamza Dairywala

Reputation: 482

You need to write orignal table name in places of topics and replies in orderBy clause.

  $forum->topics->replies()->orderBy('topics.updated_at','DESC')->orderBy('repliese.updated_at','DESC')->first();

Upvotes: 0

Amir Bar
Amir Bar

Reputation: 3105

$latestReplay = Replay::orderBy('created_at','desc')->first(); 
$lastTopic = Topic::orderBy('created_at','desc')->first();

    if ($latestReplay->created_at->gt($lastTopic->created_at)) {
          echo $lastReplay->title." is the newer!!"; 
    } else { 
          echo $lastTopic->title." is the newer!";
    }

Upvotes: 0

Rwd
Rwd

Reputation: 35190

One solution I would suggest is to have the replied touch the topics. https://laravel.com/docs/5.3/eloquent-relationships#touching-parent-timestamps

This way you can always order by the Topic's updated_at because whenever a reply is created/edited it will update the Topic as well.

To achieve this you would just need to add:

protected $touches = ['topic'];

The above is assuming that the method name for the topics relationship in the replies model is topic().

Hope this helps!

Upvotes: 1

Shuvo
Shuvo

Reputation: 303

You can try this:

$forum->replies()->orderBy('id','DESC')->get();

Upvotes: 0

Mishek
Mishek

Reputation: 86

You should have relationships between all of this models. Than you can simply:

$forum->topics->replies->sortByDesc('created_at')->first();

Read more about available methods for collections: https://www.laravel.com/docs/5.2/collections#available-methods

Upvotes: 0

Related Questions