I am working on building a basic forum (inspired by laracasts.com/discuss). When a user posts a reply to a thread:
- I'd like to direct them to the end of the list of paginated replies with their reply's anchor (same behavior as Laracasts).
- I'd also like to return the user to the correct page when they edit one of their replies.
How can I figure out which page a new reply will be posted on (?page=x
) and how can I return to the correct page after a reply has been edited? Or, from the main post listing, which page the latest reply is on?
Here is my current ForumPost
model (minus a few unrelated things) -
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class ForumPost
*
* Forum Posts table
*
* @package App
*/
class ForumPost extends Model {
/**
* Post has many Replies
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function replies()
{
return $this->hasMany('App\ForumReply');
}
/**
* Get the latest reply for a post
* @return null
*/
public function latestReply()
{
return $this->replies()->orderBy('created_at', 'desc')->first();
}
}
UPDATE
Take a look at this and let me know what you think. It's a bit weird in how it works but it's returning the correct page for a given reply ID and it's just one method:
public function getReplyPage($replyId = null, $paginate = 2)
{
$id = $replyId ? $replyId : $this->latestReply()->id;
$count = $this->replies()->where('id', '<', $id)->count();
$page = 1; // Starting with one page
// Counter - when we reach the number provided in $paginate, we start a new page
$offset = 0;
for ($i = 0; $i < $count; $i++) {
$offset++;
if ($offset == $paginate) {
$page++;
$offset = 0;
}
}
return $page;
}
$count % $paginate
will return the left over ($offset) of$count/$paginate
so11%2 = 1
, that will give you the offset. The pageno can be checked by usingfloor($count / $paginate)
.. Might be a little improvement. – Peristyle