簡體   English   中英

獲取 Laravel 分頁的總頁數並寫入文件頁碼

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM