Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.8] Add forPageBeforeId method to query builder #28011

merged 1 commit into from Mar 26, 2019


None yet
3 participants
Copy link

timacdonald commented Mar 26, 2019

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

2 checks passed

continuous-integration/styleci/pr The analysis has passed
continuous-integration/travis-ci/pr The Travis CI build passed

This comment has been minimized.

Copy link

martinbean commented Mar 27, 2019

It鈥檚 great to discover new methods like this. 鈥淧age before鈥 and 鈥減age after鈥 would be handy for cursor-like pagination.

I鈥檓 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
You can鈥檛 perform that action at this time.