andersao / l5-repository

Laravel 5 - Repositories to abstract the database layer
http://andersao.github.io/l5-repository
MIT License
4.19k stars 876 forks source link

Limit result whitout paginate #426

Open rogerio-pereira opened 7 years ago

rogerio-pereira commented 7 years ago

Hello, Good Night,

How can I limit the result, lets say to the first 5 items without paginate...

example

a blog has it's posts, the main page have the posts paginated, but a sidebar has the last 5 items... How can i get the sidebar items, if I use paginate it will get the results with pagination, i don't want to get all items and do a for...

I've tried $this->repository->orderBy('created_at','DESC')->get(10); $this->repository->orderBy('created_at','DESC')->first(10); $this->repository->orderBy('created_at','DESC')->limit(10);

$this->repository->orderBy('created_at','DESC')->paginate(10); (This one returned with paginated items

cosmok commented 6 years ago

You could do:

$this->repository->scopeQuery(function($query) {
    return $query->orderBy('created_at','DESC')
                 ->take(5);
})->all();
cbernard73 commented 5 years ago

It's relatively easy to add a limit function to the RepositoryInterface and the Eloquent/BaseRepository. To add it without breaking anything, it would need to be called before the find* functions. For example:

$this->repo->limit($limit)->findWhere([])

I think it would be better to make all the read (e.g. findWhere, findByField) methods chainable but this would be a breaking change and it would necessitate calling an additional method at the end of the chain. For example:

$this->repo->findWhere([])->limit($limit)->fetch();

What do you think? I'm happy to do a pull-request for either approach.

rogerio-pereira commented 5 years ago

i believe the first one is the better approach

eleftrik commented 5 years ago

As @cbernard73 suggests, I wrote my own implementation. I think limit() method should be part of this package - it could be useful, without the need to use paginate() which introduces custom properties in the JSON response.

mohsen-farahani commented 5 years ago

Can be used in BaseRepository


public function limit($count) {
        $this->applyCriteria();
        $this->applyScope();
        $this->model->take($count);
        return $this;
    }