Skip to content

[5.8] Add forPageBeforeId method to query builder - #28011

Merged
taylorotwell merged 1 commit into
laravel:5.8from
timacdonald:for_page_before
Mar 26, 2019
Merged

[5.8] Add forPageBeforeId method to query builder#28011
taylorotwell merged 1 commit into
laravel:5.8from
timacdonald:for_page_before

Conversation

@timacdonald

@timacdonald timacdonald commented Mar 26, 2019

Copy link
Copy Markdown
Member

On my current project, I have the need in the admin area to show a chat post in context of its surrounding posts. This allows admins to view a specific chat post that has been reported for abuse (or other potential issues) within context of the chat thread.

The following is a (terrible) example of what I mean just to illustrate the point. Post 205 is "focused". The page shows a handful of posts before, and after the focused post to give context to the admin.

-> ChatPost 202
-> ChatPost 203
-> ChatPost 204
=> ChatPost 205 👈 focused post
-> ChatPost 206
-> ChatPost 207
-> ChatPost 208

I stumbled upon the existing forPageAfterId method which is mostly sugar over some other methods. This is an undocumented method, and is perhaps meant for internal use (i.e. the chunkById method), however it is the perfect tool for retrieving the posts following the focused post. Unfortunately it only shows the page after the given ID, but I am also looking for the page before so I can show the post in context.

This PR introduces the complementary method forPageBeforeId($perPage, $lastId, $column).

This allows a developer to do something like this...

$posts = new Collection;

$posts = $posts->concat(ChatPost::forPageBeforeId(15, $focused->id)->get()->reverse());

$posts = $posts->push($focused);

$posts = $posts->concat(ChatPost::forPageAfterId(15, $focused->id)->get());

which results in a collection of posts that contain the focused post, with 15 posts on either side of the focused post, sorted chronologically.

@timacdonald timacdonald reopened this Mar 26, 2019
@taylorotwell
taylorotwell merged commit bed0b2a into laravel:5.8 Mar 26, 2019
@martinbean

Copy link
Copy Markdown
Contributor

It’s great to discover new methods like this. “Page before” and “page after” would be handy for cursor-like pagination.

I’m thinking about the naming though. If the column to page before/after is configurable, something like ->forPageBeforeId(10, 0, 'created_at') no longer makes sense if you want to page based on something like models’ created_at timestamps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants