我有一个laravel
-应用程序,我想在其中为我的"博客文章"-部分当我返回所有blog_posts时,我可以让它工作,但由于它们已经分类,分页不再工作。
这是我的控制器
public function index() {
$blog_posts = Blog::where("publishes_on", "<=", Carbon::now())
->orderBy('publishes_on', 'desc')
->where('blog_status_id', '=', '2')
->with('blog_category')
->paginate(4);
$blog_categories = BlogCategory::get();
return view('blog.index', compact('blog_categories', 'blog_posts'));
}
和刀片视图
@foreach($blog_categories as $category)
@foreach($category->blog_posts as $blog)
<div>
<a href="/blog/{{ $blog->slug }}">{{ $blog->title }}</a>
</div>
@endforeach
@endforeach
在我添加类别之前,我的刀片视图看起来像这个
@foreach($blog_posts as $blog)
<div style="border-top: 2px solid red; padding: 4px;">
<a href="/blog/{{ $blog->slug }}">{{ $blog->title }}</a>
</div>
@endforeach
<div>
{{ $blog_posts->links() }}
</div>
但是现在,我不知道如何添加分页?
有人能帮我解决吗
您可以使用setRelation
来覆盖blog_posts关系,并让它返回一个分页集合:
<?php
$blog_categories = BlogCategory::get()
->map(function($blogCategory) {
return $blogCategory
->setRelation( 'blog_posts', $blogCategory->blog_posts()->paginate(10) );
});
调用paginate()
返回一个IlluminatePaginationLengthAwarePaginator
实例
要获取博客文章的集合,请使用此:
$category->blog_posts->getCollection()
要获得分页链接视图:
$category->blog_posts->links()
这都是未经测试的,所以如果不起作用,请告诉我
您可以创建自定义分页:(https://laravel.com/api/5.8/Illuminate/Pagination/LengthAwarePaginator.html)
$all_posts = Blog::where("publishes_on", "<=", Carbon::now())
->orderBy('publishes_on', 'desc')
->where('blog_status_id', '=', '2')
->with('blog_category')
->get();
$blog_categories = BlogCategory::get();
$count = count($all_posts);
$page = (request('page'))?:1;
$rpp = 4; //(request('perPage'))?:10;
$offset = $rpp * ($page - 1);
$paginator = new LengthAwarePaginator(
$all_posts->slice($offset,$rpp),$count,$rpp,$page,[
'path' => request()->url(),
'query' => request()->query(),
]);
$blog_posts = $paginator;
return view('blog.index', ['blog_posts' => $blog_posts,
'blog_categories' => $blog_categories]);