murilo's avatar
Level 10

Laravel Many to Many with Pagination

Hello guys , I don´t know if some one can help me . I did a many to many Laravel relation ship in a Post Table and in a Tags Table . Like this example - https://laracasts.com/series/laravel-5-fundamentals/episodes/21

It worked fine , but I want to find and paginate all the POST that has a TAG selected , like this -

www.mywebsite.com/posts?tag=4

So I did a many to many relation ship like this in the post page -

$post_with_tags = PostTag::findOrFail(4)->post;

It is working fine , it is showing all the POSTs that has the tag 4 , but the problem is that I cant paginate like this , if I try to do it -

$tag= PostTag::findOrFail(4)->post->paginate($20);

It will gives me an Error .

The only way that I found to do it , is making two searches , that does not look like the best ways -

  • First I search the IDs of the Post with many to many relation ship like this , and will return me those IDS - 1,4,6 ... .
  • And after with the IDs , I make another search of the POST with those IDS that I found [1,4,6 .... ] , like this -
SEARCH 1 -
$ids_that_i_found_in_many_to_many_TAGS =  [1,4,6 .... ] ;

SEARCH 2  with pagination -
$post = Post::orderBy('created_at', 'desc')where('id' ,  $ids_that_i_found_in_many_to_many_TAGS )->paginate(20);

Does have another way to do that ? That I can make a Laravel many to Many relation ship with pagination with just one search ?

Thanks a Lot .

0 likes
4 replies
d3xt3r's avatar
d3xt3r
Best Answer
Level 29

What error ? $20 ??

Try this ...

$posts = PostTag::findOrFail(4)->post()->paginate(20);
1 like
murilo's avatar
Level 10

Hello My Friend , Thanks for replying . I tried this and It gave me this error -

BadMethodCallException in Macroable.php line 74:
Method paginate does not exist.
murilo's avatar
Level 10

You where right , Now it is is ok . Thanks . Instead doing this -

$post_with_tags = PostTag::findOrFail(4)->post;

I have to do it -

$posts = PostTag::findOrFail(4)->post()->paginate(20);

Now it is working .

Please or to participate in this conversation.