Reputation: 1741
I'm using Laravel 5 to build a discussion forum. Each forum has threads, and each thread has replies. I can't find anything on how to get the URL of the latest reply to a thread - right now I have this function to show the forum:
public function show($slug)
{
$forum = $this->forums->getBySlug($slug);
return view('forum.show', compact('forum'));
}
Then in that view I have a basic @forelse
to show the HasMany
related threads:
@forelse($forum->threads as $thread)
<tr>
<td><a href="{{ route('forum.thread', [$forum->slug, $thread->slug]) }}">{{ $thread->title }}</a></td>
<td>{{ $thread->replies->count() }} Replies</td>
<td>{{ $thread->replies->last()->author->username or 'No recent activity' }}</td>
</tr>
@empty
<tr>
<td colspan="3" class="text-center">There aren't any threads in this forum</td>
</tr>
@endforelse
This works fine, but I would like the username of the most recent reply to be linked to the actual reply with a url like http://example.com/forum/thread-title-here/?page=3#12345
where the fragment is the reply ID. I can't figure it out, any ideas? I also get the error Call to undefined method Illuminate\Database\Eloquent\Collection::paginate()
when using $thread->replies->paginate(10)
to try and calculate the number of pages the thread has, but that brought up another issue regarding posts linked on other pages.
Does anyone have any ideas?
Upvotes: 0
Views: 428
Reputation: 106
Just ran into a similar issue. Try this:
threads.model
// probably what you have now
public function replies() { return hasMany('Reply');}
You can add a second relation to the replies model like this:
// add this relation which has a filter
public function latestReply() { return hasOne('Reply')->last();}
Now when you want the latest reply, you can do this:
$forum = $this->forums->getBySlug($slug)->with('threads','threads.latestReply');
and in your view:
@foreach($forum->threads as $thread)
{{$thread->latestReply->id}}
@endforeach
I learned this from http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/
The original link no longer works. Click here to visit the Google cached version
Hopefully I have translated this to your situation. You might want to review the link, it's more informative than I am.
Upvotes: 1
Reputation: 3658
You don't provide enough code to give a detailed response, but for the sake of an example and assuming you use Laravel's naming conventions:
// Eager load threads and their replies
$forum = Forum::with(array('threads.replies' => function($q) {
// For each thread, get the most recent reply
$q->orderBy('some_date_column', 'desc')->take(1);
}))->get();
From the code you provided it seems that you would need to modify your getBySlug() method.
Upvotes: 0