0

I have two tables Posts and Tags with many to many relation. I need to retrieve all posts by some tag and paginate it. Is it possible to do with paginate method or I need to create a new instance of Paginator and do everything by hand?

P.S. Need something like:

$tags = Tags::where('name', '=', $tag)->with('posts')->first();

$posts = $tags->posts->paginate(5);

return view('blog/posts')->with('posts', $posts);
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
user1692333
  • 2,461
  • 5
  • 32
  • 64

2 Answers2

0

You should probably use:

$posts = $tags->posts()->paginate(5);

and you should also rename $tags to $tag if you are getting only one record to not make variable name misleading.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
0

You have to use a join statement. It should look something like this:

DB::table('tags')
        ->join('posts', 'tags.id', '=', 'posts.tag_id')
        ->where('tags.name', '=', $tag)
        ->paginate(5);
Mehrdad Hedayati
  • 1,434
  • 13
  • 14