[英]Get total pages of pagination Laravel and write to file page number
我有一个代码:
$posts = Post::paginate(100);
如何 foreach 分页页面并显示结果? 我需要在每个文件中写一篇文章。
foreach($posts as $page => $post) {
//put on file current links posts of current page with file name: file-posts-$page.txt
}
我该怎么做?
我试过:
for ($currentPage = $posts->perPage(); $currentPage <= $posts->total(); $currentPage++) {
Paginator::currentPageResolver(function () use ($currentPage) {
return $currentPage;
});
//put on file links of current posts of current page with file name: file-posts-$page.txt
}
但我没有得到需要我的结果。 每 1 个帖子我得到 1 个文件..
如果我理解正确,您希望检索所有可能页面的结果。 如果是这样,您可以改用模型块。 这就是它在您的情况下的工作方式:
Post::chunk(100, function(Collection $posts, $page) {
// Do what you want to do with the first 100 using $posts like this
foreach($posts as $key => $post) {
// Do stuff with $post
}
// You have access to $page here
//put on file links of current posts of current page with file name: file-posts-$page.txt
});
由于您的每页是 100,我将 100 传递给 chunk 方法,该方法将检索前 100 个,然后检索下一个 100,以此类推。 传递给它的第二个参数是一个回调,每块 100 个结果和当前页面将被传递到。
我希望这有帮助。
你可以试试这个。
$posts = Post::paginate(100);
foreach($posts as $page => $post) {
}
{{$posts->links()}}
如此处所述,您可以使用
$paginator->lastPage()
这是第一个项目索引:
$paginator->firstItem(); // Get the result number of the first item in the results.
这是当前页面中的最后一项:
$paginator->lastItem() //Get the result number of the last item in the results.
例如:
这是控制器:
public function index(Request $request)
{
$perPage = (int)$request->query('per_page') ?: API_DEFAULT_PER_PAGE;
$posts = Post::orderBy('created_at', 'desc')->paginate($perPage);
...
return view('admin.posts.index', ['posts' => $posts]);
}
这是刀片:
@extends('layouts.admin')
@section('title', title('posts'))
@section('content')
<h1 class="fw-200 admin-heading__title">posts</h1>
{{$posts->count()}} of {{ $posts->total() }}
<a class="btn btn-outline-primary" href="{{ route('admin.posts.create') }}">create</a>
<div>
<table>
<tbody>
@forelse($posts as $post)
....
@empty
<tr>
<td colspan="6" class="text-muted">No items.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
{{ $posts->appends(request()->query())->links() }}
@endsection
或使用
{{ $posts->links() }}
对于第一个项目的索引,您可以使用 ->first
{{$posts->count()}} of {{ $posts->total() }}
我在分页或标题旁边使用它
Posts: ( from {{$posts->firstItem()}} to {{ $posts->lastItem()}} in {{ $posts->total() }} item(s))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.