Reputation: 545
I am querying DB posts via a Laravel eloquent controller and would like to first filter the posts and then paginate.
$filter = ['author_id' => $id, 'status' => 'live', 'type' => $type];
$posts = Post::where($filter)->orderBy('id','desc')->get();
$posts = Post::paginate(1, ['*'], 'page', $page);
return $posts;
Of course currently it is only going to paginate. How can I combine both $posts
so that the filtered results are paginated?
Thanks!
Upvotes: 0
Views: 188
Reputation: 1585
You can also simplify the solution like this and this will become more flexible.
$filter = ['author_id' => $id, 'status' => 'live', 'type' => $type];
$posts = new Post();
$posts = $posts->where($filter);
$posts = $posts->orderBy('id','desc');
$posts = $posts->paginate(1, ['*'], 'page', $page);
return $posts;
Upvotes: 0
Reputation: 4392
As simple as just chain those methods like:
$posts = Post::where($filter)
->orderBy('id','desc')
->paginate(1, ['*'], 'page', $page);
Upvotes: 2