Laravel Pagination after get

Viewed 195

I'm trying to paginate my collection that I've generated with below codes

$vehicles = Vehicle::whereHas('destinations', function($q) use($id){
                            $q->where('destination_id',$id)
                            ->where('active',1);
                            })->get();

The collection i've recieved from above is looped again.

foreach ($vehicles as $key => $vehicle) {
            # code...
            $perday_rate = $vehicle->destinations->where('id',$destination_id)->first()->pivot->day_rate;
            $pernight_rate = $vehicle->destinations->where('id',$destination_id)->first()->pivot->night_rate;
            $day_rate = $perday_rate*$days;
            $night_rate = $pernight_rate*$nights;
            $total_amount = $day_rate+$night_rate;
            $vehicle['total_amount'] = $total_amount;
            $vehicle['availability'] ='true';

            if($vehicle->whereHas('unavailability', function($q) use($fdate,$tdate){
                                $q->whereRaw("? BETWEEN `from_date` AND `to_date`", [$fdate])
                                    ->orwhereRaw("? BETWEEN `from_date` AND `to_date`", [$tdate]);
                            })->count()>0){
                $vehicle['availability'] = 'false';
            }

Since, collection couldn't be paginated directly, i've added below manual codes for pagination:

$page = 1;
            $perPage = 1;
            $vehilces= new \Illuminate\Pagination\LengthAwarePaginator(
                $vehicles->forPage($page, $perPage), 
                $vehicles->count(), 
                $perPage, 
                $page
            );

In my view, i've rendered like:

@foreach ($vehicles as $vehicle)
        @include('includes.searchVehicle')
    @endforeach
    {{$vehicles->links()}}

The pagination button is displayed in the frontend but when I click on next, the URL converts to

http://localhost:8000/?page=2

This throws error as there is not route available for this route. I've also tried setting custom URL:

$vehicles->setPath('/destination/'.$destination->slug);

But only URL is changed, search result remains in the same page

1 Answers

I've solved this issue. The issue was in the static $page=1. I've changed this to

            $page = LengthAwarePaginator::resolveCurrentPage()??1;

Works perfectly

Related