NikkiLoveGod's avatar

Sorting and pagination with repositories

Hi,

How would I go about implementing sorting and pagination when I am using repositories?

Lets say that I have a method in repository like $this->userRepository->getUsersInGroup($groupId). How do I implement pagination and sorting in that case?

0 likes
6 replies
Jinggo's avatar

You can do this return $this->model->whereGroupId($groupId)->paginate(10); where model is an Eloquent class

NikkiLoveGod's avatar

Yes, but is it wise to expect eloquent models with sorting and pagination possibilities from the repository? It couples them very tightly together.

Or should I have custom sorting / pagination class that does it? Well, I think I could do $this->userRepository->getAllSortedByName etc, and then create the pagination separately. Any thoughts?

joedixon's avatar

Are you using interfaces? If so, and this repo is an eloquent specific implementation, then I would say that @Jinggo's response is the way to go.

Amperative's avatar

@NikkiLoveGod did you find a good solution in the end to this conundrum? I agree - putting pagination in the repo is a tight coupling and it makes that function less usable around your app (unless you want pagination in ALL uses of the repo method).

voff's avatar

The answer should be: The place where you put your business logic.

When you have already decoupled your database logic with repositories, have you done this the same for your business logic? I personally do this by extracting all of the business logic into services. This blog post explains it pretty good.

Amperative's avatar

@voff thanks for that.

Presumably this implies you can have a service that sits between the controller and the repo to handle things of this (pagination) nature?

Can you hint at how the repo and service would work together to provide a de-coupling of pagination? Or rather, can you provide a code example of using a repo and a service to provide pagination/sorting functionality?

Please or to participate in this conversation.