LRAVEL 8 分页不存在,我需要按 region_id 选择数据并分页

问题描述

我在 Laravel 文档中找到了 paginate() 方法。但是,当我实施它时它不起作用。我收到分页不存在的错误。我知道分页可能只适用于 all(),但我只需要几列,并且我需要像在 show 方法中那样按区域选择数据。如何重写索引并显示方法以使其工作?

索引方法

public function index()
{

    $tournaments =  Tournament::latest()
        ->get(['title','city','date_starter_at','slug'])->paginate(12);

    $regions = Region::all();
}

显示方法

public function show(Tournament $tournament)
{
    return view('tournaments.show',[ 'tournament' => $tournament,'regions' => Region::where("id","=",$tournament->region_id)->get(),]);
    

    return view('tournaments.index',[
    'regions' => $regions,'tournaments' => $tournaments,]);
}

解决方法

您正在对集合调用 paginate。您应该在查询构建器实例上调用它。

public function index()
{
    $tournaments =  Tournament::select(['title','city','date_starter_at','slug'])
                                ->latest()
                                ->paginate(12);
    $regions = Region::all();

    return view('tournaments.index',compact('tournaments','regions');
}

public function show(Tournament $tournament)
{
    $tournament->load('region');

    return view('tournaments.show',compact('tournament'));
}

此外,您还可以通过为 Tournament 添加关系并将其加载到 show 方法中来稍微整理一下代码。

Tournament.php

public function region()
{
    return $this->belongsTo(Region::class);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...