1
votes

I'm going to create blog in Laravel. Now I get post form category in the blog and I can only show paginate according to post but I want to show paginate only for posts that have relations with category id

I have some problem in my code, please help me to fix my problem.

In the controller source code:

//this code show posts according to category id
$postCatId = $request->postCatId;
$postList =PostCat::with("posts")->where('id',$postCatId)->get();

//this code show paginate according to posts has relation with category
$paginate=PostCat::with("posts")->where('id',$postCatId)->paginate(2);

This then returns $postList and $paginate to view

in View:

//show posts has relation with category id
@foreach($PostList as $post)
     @foreach($post->posts as $post_item)
     {{$post_item->id}}
     @endforeach
@endforeach


//show paginate according to posts has relation with category id
{{$paginate->links()}}

But I cannot show paginate with posts that has relation with category id

2
You want to paginate all posts which have a category? Because now you're paginating categories, but not posts.Alexey Mezenin
exactly ,with this code only paginate for category but i wants to show paginate according to posts has relational with categoryalireza

2 Answers

0
votes

If you want to paginate posts that have a category, use this query instead of two current ones:

$posts = Post::with('category')
             ->has('category')
             ->where('id', $postCatId)
             ->paginate(2);

Make sure you have category() relationship in the Post model:

public function category()
{
    return $this->belongsTo('App\PostCat');
}

In a view iterate over $posts and render links:

@foreach($posts as $post)
    <div>Post ID is {{ $post->id }} and category ID is {{ $post->category->id }}</div>
@endforeach

{{ $paginate->render() }}
0
votes

The easier way for many to many relationship in Laravel 5 and paginate this:

Category Model:

public function articles()
{
    return $this->belongsToMany('App\Article');
}

Article Model:

public function categories()
{
    return $this->belongsToMany('App\Category');
}

When you want to download all the posts/articles from the category with the pagination:

$category = Category::where('slug', $slug)->firstOrFail();
$category_articles = $category->articles()->orderBy('created_at', 'desc')->paginate(10);