0

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!

2 Answers 2

2

As simple as just chain those methods like:

$posts = Post::where($filter)
    ->orderBy('id','desc')
    ->paginate(1, ['*'], 'page', $page);
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Makes sense now - thought the :: was required for each.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.