繁体   English   中英

具有带有分页的laravel类别(基于条目)帖子

[英]having laravel category (slug based) posts with pagination

我有这个功能,在这里我得到我的类别基础上,他们的slug

public function postcategoryposts($slug){
  $category = PostCategory::where('slug','=',$slug)->firstOrFail();
  return view('front.postcategory-posts', compact('category'));
}

目前,我在刀片中获取每个类别的帖子,例如:

@foreach($category->posts as $post)
  {{$post->title}}
@endforeach

直到这里一切正常,问题是如何将我的帖子分成几页? 我无法使用:

$category = PostCategory::where('slug','=',$slug)->paginate(10);

因为我在用

firstOrFail();

任何想法?

您需要向模型中添加函数以获取帖子,然后分页。

在您的控制器中

public function postcategoryposts($slug)
{
  $category = PostCategory::where('slug','=',$slug)->firstOrFail();
  $posts = $category->getPaginatedPosts(10);
  return view('front.postcategory-posts', compact('posts'));
}

在您的模型中

// PostCategory model
public function getPaginatedPosts($limit = 10)
{
  // Get category posts using laravel pagination method
  return Post::where('category_id', '=', $this->id)->paginate($limit);
}

在您的刀片视图中

<div class="container">
    @foreach ($posts as $post)
        {{ $post->title }}
    @endforeach
</div>

{{ $posts->render() }}

有关Laravel分页的更多信息,请点击此处

希望对您有帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM