[英]having laravel category (slug based) posts with pagination
I have this function, where i get my categories base on their slug
我有这个功能,在这里我得到我的类别基础上,他们的
slug
public function postcategoryposts($slug){
$category = PostCategory::where('slug','=',$slug)->firstOrFail();
return view('front.postcategory-posts', compact('category'));
}
Currently i'm getting my each category posts in blade like: 目前,我在刀片中获取每个类别的帖子,例如:
@foreach($category->posts as $post)
{{$post->title}}
@endforeach
until here everything is normal, the problem is how to divide my posts into pages? 直到这里一切正常,问题是如何将我的帖子分成几页? I am not able to use:
我无法使用:
$category = PostCategory::where('slug','=',$slug)->paginate(10);
because I'm using 因为我在用
firstOrFail();
any idea? 任何想法?
You need to add a function to your model to get posts and then paginate. 您需要向模型中添加函数以获取帖子,然后分页。
In your controller 在您的控制器中
public function postcategoryposts($slug)
{
$category = PostCategory::where('slug','=',$slug)->firstOrFail();
$posts = $category->getPaginatedPosts(10);
return view('front.postcategory-posts', compact('posts'));
}
In your model 在您的模型中
// PostCategory model
public function getPaginatedPosts($limit = 10)
{
// Get category posts using laravel pagination method
return Post::where('category_id', '=', $this->id)->paginate($limit);
}
In your blade view 在您的刀片视图中
<div class="container">
@foreach ($posts as $post)
{{ $post->title }}
@endforeach
</div>
{{ $posts->render() }}
More informations about Laravel pagination here 有关Laravel分页的更多信息,请点击此处
Hope it's helps you :) 希望对您有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.