scopeak
scopeak

Reputation: 545

How to use multiple arguments when querying Laravel Eloquent results

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

Answers (2)

Jesus Erwin Suarez
Jesus Erwin Suarez

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

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

As simple as just chain those methods like:

$posts = Post::where($filter)
    ->orderBy('id','desc')
    ->paginate(1, ['*'], 'page', $page);

Upvotes: 2

Related Questions