简体   繁体   English

分页 laravel 集合返回 404

[英]Paginate laravel collection return 404

I have paginated my collection and it shows pagination but when I click on page numbers it return 404 error我已经对我的收藏进行了分页,它显示了分页,但是当我单击页码时,它返回 404 错误

Route

Route::post('search', 'front\SearchController@results')->name('search');

Blade (form)

<form action="{{route('search')}}" method="POST">
  @csrf
  @method('POST')
  <input  class="input" type="search" name="q">
</form>

Controller

public function results(Request $request) {
  $q = $request->input('q');
  $rres = array_merge('//my data...');
  $perPage = 12;
  $page = null ?: (Paginator::resolveCurrentPage() ?: 1);
  $items = $rres instanceof Collection ? $rres : Collection::make($rres);
  $rres = new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, [
    'path' => Paginator::resolveCurrentPath()
  ]);
  return view('front.pages.new-search', compact('q', 'rres'))->withQuery($q);
}

Blade (pagination)

{{$rres->links('front.pages.search-paginate')}}
// URL of other pages is like:
// http://example.com/search?page=2
// while url of page 1 is like
// http://example.com/search (refer to route code above)

Any idea?任何想法?

Links only support GET and HEAD methods, try to add:链接只支持GETHEAD方法,尝试添加:

Route::get('search', 'front\SearchController@results')->name('search');

Note that you only have to add above, no need to remove your POST -method from routes.请注意,您只需在上面添加,无需从路由中删除您的POST方法。

You are missing the return statement in your results method.您在results方法中缺少 return 语句。

return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, [
    'path' => Paginator::resolveCurrentPath()
]);

Edit: I see you are returning a view after an HTTP POST which is really a bad design choice.编辑:我看到您在 HTTP POST 之后返回视图,这确实是一个糟糕的设计选择。 You can google about the PRG Pattern and you will find many articles that will explain why you should always redirect to an HTTP GET which will render your view.你可以在谷歌上搜索 PRG 模式,你会发现很多文章解释了为什么你应该总是重定向到 HTTP GET 来呈现你的视图。

Instead, you should use a GET request for this.相反,您应该为此使用 GET 请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM