princeoo7's avatar

Paginate BelongsToMany relationship records if more than set limit

How do we paginate records for belongsToMany relationship ?

i was watching laracasts lesson: Laravel From Scratch: Part 31 - Sorting Posts By Tags url : https://youtu.be/Lq9rOAYW-S0

but there is not part talking about pagination for relational records : (

my code is as below:

 public function index(Category $category)
    {
        $posts = $category->posts;
        dd($posts);
        return view('pages.frontend.categories.index', compact('posts'));
    }

i get around 50 records for the current category i am checking post for. I want to have a limit of 20 record per page.

if i do :

$posts = $category->posts->paginate(20);

i get error:

 BadMethodCallException
 Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

0 likes
4 replies
RoboRobok's avatar
Level 7

You almost made it:

$posts = $category->posts()->paginate(20);

Any Query Builder in Laravel has access to paginate() method and relationship called as a method behaves like a Query Builder.

Relationship called as a property is Eloquent Collection, which doesn't have paginate() method.

1 like
jeffrey_no_way's avatar

there is no method called paginate in the collection class

//this is not correct
$posts = $category->posts->paginate(20);
// querying the relationship
$posts = $category->posts()->paginate(20);
1 like

Please or to participate in this conversation.