php - show paginate according to data in relation table in laravel
Get the solution ↓↓↓Solution:
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 havecategory()
relationship in thePost
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() }}
Answer
Solution:
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);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: you must enable the openssl extension in your php.ini to load information from https://repo.packagist.org
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.