Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Paginator get item page

I'm implementing a forum system. The application will have a following system and every user will be able to see activity from their friends. So, when a friend of mine posts something in a forum I should see an item in my feed saying "Your friend replied to forum...".

Every thing is fine 'til here but I want to achieve something like this:

My feed should also have a link to that forum which will take me to the page where my friend's reply is. This page will not be always the last.

So, my question is, if I know the $reply->id of my friend's reply and I'm paginating all the replies of the forum, how can I know in which page is my friend's reply?? Is this easy or I'm asking too much??

like image 905
Javier Enríquez Avatar asked Nov 03 '14 01:11

Javier Enríquez


1 Answers

It depends on what you are using to sort the replies. This example assumes the user has selected newest and we are using created_at to determine time of posting.

In the feed, to show the page where the reply is

$reply->getLink()

in Reply Model:

public function getLink($per_page = 10)
{
    //assumes ordered by newest
    $newer = $this->forum()->replies()->orderBy('created_at','desc')->where('created_at','>',$this->created_at)->count();
    $page = ceil($newer/$per_page);
   return url(sprintf('forums/%s/replies/%s?per_page=%s&page=%s',$this->forum_id,$this->id, $per_page,$page);
}

If the total posts are 30 and the one you want is the 18th then the link will be

    $newer = 30-18 = 12
    $page = ceil(12/10) = 2

/forums/{id}/replies/{id}?per_page=10&page=2

The one flaw I can see with this method is if the number of posts posted at the exact second are more than the number of replies shown per_page.

like image 188
ralphowino Avatar answered Nov 02 '22 05:11

ralphowino