-1

I found the paginate() method in the Laravel documentation. However, it doesn't work when I implement it. I get an error that paginate does not exist. I know paginate is maybe only for all(), but I need only a few columns, and I need to select the data by region like in the show method. How can I rewrite the index and show methods to get it to work?

Index method

public function index()
{

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

    $regions = Region::all();
}

Show method

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,
        ]);
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Tom_hutka
  • 15
  • 4
  • 1
    you can't use `paginate` after the `get` method. `Tournament::latest()->select(['title', 'city', 'date_starter_at', 'slug'])->paginate(12);` ` – Ravisha Hesh Jan 31 '21 at 08:06

1 Answers1

2

You are calling paginate on a collection. You should call it on a query builder instance.

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'));
}

Also you can tidy up your code a bit by adding a relationship for Tournament and loading it in the show method.

Tournament.php

public function region()
{
    return $this->belongsTo(Region::class);
}
tamrat
  • 1,815
  • 13
  • 19