【问题标题】:laravel pagination returns different pagelaravel 分页返回不同的页面
【发布时间】:2019-08-05 21:16:37
【问题描述】:

我正在做一个 laravel 项目,我从 API 获取数据,然后我想在页面上显示它。我希望回报分布在 4 页上,每页有 10 个结果。到目前为止,我所拥有的似乎应该可以工作,但是我缺少一件,因此将不胜感激任何建议和帮助。所以这就是假设使用代码的方式:

1) 用户在搜索框中输入书名。

<form method=POST action='/search'>
        @csrf
        <input type="text" name="search_term"/>
        <input type="submit" value="Search"/>
    </form>

2) 然后将输入发送到我的控制器,该控制器查询 google book api。

class search extends Controller {
public function search(){
    $current_page = LengthAwarePaginator::resolveCurrentPage();
    echo $current_page;
    $term = request('search_term');
    $term = str_replace(' ', '_', $term);
    $client = new \Google_Client();
    $service = new \Google_Service_Books($client);
    $params = array('maxResults'=>40);
    $results = $service->volumes->listVolumes($term,$params);
    $book_collection = collect($results);
    $current_book_page = $book_collection->slice(($current_page-1)*10,10)->all();
    $books_to_show = new LengthAwarePaginator($current_book_page,count($book_collection),10,$current_page);
    return view('library.search')->with(compact('books_to_show'));
    }
}

3) 然后结果会显示在我的刀片上

@extends('home')
@section('content')
@foreach($books_to_show as $entries)
<div class="row">
    <div class="col-sm-auto">
        <img class="w-50 img-thumbnail" src={{$entries['volumeInfo']['imageLinks']['smallThumbnail']}}/>
    </div>
    <div class="col-sm">
        {{$entries['volumeInfo']['title']}}<br/>
        @if($entries['volumeInfo']['authors']!=null)
        by: 
        @foreach($entries['volumeInfo']['authors'] as $authors)
            {{$authors}}
        @endforeach
        @endif

    </div>
</div>

@endforeach
{{$books_to_show->links()}}
@endsection

这一切都可以正常工作并且符合预期。我在视图上得到 10 个结果,然后我在底部有一个栏,它显示了 4 个不同的页面可供选择。

当我第一次输入“William Shakespeare”等搜索词时,我的页面网址是: localhost:8000/search

但是,当我点击任何页面时,我的网址变为: http://localhost:8000/?page=2

我了解 ?page=* 是分页确定您正在查看的页面的方式,并且应该将其发送回控制器。但是,我在将其发送回我认为的控制器时遗漏了一些东西。

对此仍然很新鲜,因此非常感谢任何建议。

【问题讨论】:

    标签: php laravel pagination


    【解决方案1】:

    LengthAwarePaginator 在其构造函数中接受第 5 个参数:一个选项数组。

    path 选项

    $books_to_show = new LengthAwarePaginator($current_book_page, count($book_collection), 10, $current_page, [
        // This will fix the path of the pagination links
        'path' => LengthAwarePaginator::resolveCurrentPath()
    ]);
    

    顺便说一下,在完全不同的情况下,Laravel 通过为您分割集合让您的生活更轻松,请查看:

    $current_book_page = $book_collection->forPage($current_page, 10);
    

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 2017-06-28
      • 1970-01-01
      • 2018-08-23
      • 2014-09-16
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2010-09-24
      相关资源
      最近更新 更多