我有一个代码:
$posts = Post::paginate(100);
我如何浏览分页并显示结果?我需要在每个文件中写一个帖子。
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个文件。
答案 0 :(得分:0)
如果我正确地理解了您,您想检索所有可能页面的结果。如果是这样,您可以改用模型块。这就是您的情况下的工作方式:
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传递给了块方法,该方法将依次检索前100个和随后的100个。传递给它的第二个参数是一个回调,每个100个结果块将被传递到当前页面。
您应该查看有关块方法here
的更多信息我希望这会有所帮助。
答案 1 :(得分:0)
您可以尝试一下。
$posts = Post::paginate(100);
foreach($posts as $page => $post) {
}
{{$posts->links()}}
答案 2 :(得分:0)
根据记录here,您可以使用
$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))