phplaravellaravel-8laravel-controllerlaravel-datatables

LRAVEL 8 paginate does not exist, i need select data by region_id and paginate it


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,
        ]);
}

Solution

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