How can i deploy pagination after foreach loop in laravel

  foreach, laravel, mysql, pagination, php

I’m trying to create a pagination in my search result. I have one queries in my repository like:

public function getFilteredVehicles($id,$pax,$categories,$search_type,$from_date,$to_date)
    $vehicles = Vehicle::whereHas('destinations', function($q) use($id){

    if($search_type == 'disposal' || $search_type == 'pnd')
        $vehicles = $vehicles->where('registered_location',$id);

        $vehicles = $vehicles->where('vehicle_categoryid',$categories);

    return $vehicles;

The returned result again needs to be processed via loop like:

public function calculateLocationAmount($vehicles,$fdate,$tdate,$destination_id)
    $datetime1 = new DateTime($fdate);
    $datetime2 = new DateTime($tdate);

    $interval = $datetime1->diff($datetime2);
    $days = $interval->format('%a');
    $days = $days+1;
    $nights = $days-1;

    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]);
            $vehicle['availability'] = 'false';
    return $vehicles;

This final result needs to be paginated. How can i do it?

Using foreach is changing the value to collection due to which links is not working. If i don’t do paginate() or get(), for loop is not executed.

Kindly help.

Source: Ask PHP