I'm working on a "forum like" app and when viewing a thread, a user can also choose to view a post in a thread (an specific one).
The URL can be something like /thread/29?post=22
. Now, a thread can have many posts. Therefore, since it's paginated with 10 posts per page, a post can be in any page depending on when it was posted.
I have no way of knowing which page the post is on in the record.
Note the pagination record is dynamic.
My code:
$posts = Post::where('thread_id', $thread->id)->paginate(10);
//there are over 50+ posts for instance
My simplified view:
@foreach ($posts as $post)
<span id="post{{ $post->id }}">Post #{{ $post->id }}</span>
{{ $post->body }}
@endforeach
My example URL would look like: http://example.com/thread/1
How would I know which page has a specific post? Say I want to go to the post with ID 28 which belongs to thread with an ID 1. How would I know which page of the result that thread is in?
I want to do something like:
http://example.com/thread/1?post=28&page=2 //authomatically guessed that post 28 would be in page 2.
how can do do this? Thanks!
Divide post id by 10 and ceil value. That is of course if each post in thread starts with 1 and increments by 1.
$page = ceil($post->id / 10);
If your post id's are dynamic then retrieve all posts from a thread ordered by post date and iterate through results to find position of searched id. I'm not a laravel developer so not sure about query syntax but something like this:
$searching_id = 28; // searching for page of post id 28
$post_index = 0; // position of post in ordered posts array
$posts = Post::where('thread_id', $thread->id)->order_by('post_date'); // get all posts ordered by post_date or whatever table field is for post date
foreach ($posts as $post) {
if ($post->id == $searching_id) {
break;
}
$post_index++;
}
$page = (int)($post_index / 10) + 1;
Heres how I did it:
$post_id = 28;
$posts_per_page = 10;
$posts = Post::where('id', $thread->id)->get();
foreach ($posts as $key => $value) {
if ($value->id == $post_id) {
$page = ceil(($key + 1) / $posts_per_page);
break;
}
}
// $page = 2
$post_id = 28;
$posts_per_page = 10;
$posts = Post::where('id', $thread->id)->get(['id'])->flip();
$index = $posts[$post_id]
$page = ((int) ($index / $posts_per_page) + 1