Shawn Sonnier
Shawn Sonnier

Reputation: 533

Laravel: Add pagination to query

How can I add paginate to this query? The pagination data is not showing in my json response.

  $posts = Post::with('comments','settings')
    ->whereIn('user_id', function($query)
        use($id){
            $query->select('followable_id')
            ->from('followables')
            ->where('user_id', $id)->paginate(10);
        }
    )->orWhere('user_id', $id)
        ->latest()
        ->get();

    return response()->json($posts);

Upvotes: 0

Views: 36

Answers (2)

Firman Putra
Firman Putra

Reputation: 142

->paginate(10);

The paginate should be on the outside of the query (not within the whereIn closure)

Try to swap ->get(); with ->paginate(10);

Upvotes: 1

Don't Panic
Don't Panic

Reputation: 14520

A quick check of the docs shows:

You may call paginate after setting other constraints on the query, such as where clauses:

Note it says after other constraints - it doesn't make sense to use pagination inside a whereIn() clause. So in your case, that would be something like:

$posts = Post::with('comments','settings')
    // ... your code, no pagination ...
    )->orWhere('user_id', $id)
        ->latest()
        ->paginate(10);

Upvotes: 1

Related Questions