How to paginate an array in Laravel

In Controller::

<?php

namespace App\Http\Controllers\Frontend;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class HomeController extends Controller
{
public function index(Request $request)
{
//start popular cities
$popularCityArray = array();
$cityRepo = new CityRepository();
$popularCityRepo = new PopularCityRepository();
$popular_cities = $popularCityRepo->getObjs();

foreach($popular_cities as $popular_city){
$cityObj = $cityRepo->getObjByID($popular_city->city_id);
$cityObj->order = $popular_city->order; //bind order to city obj
//add city obj to city array
array_push($popularCityArray, $cityObj);
}
//end popular cities

//start paginating popular cities array
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$col = new Collection($popularCityArray);
$perPage = 3;
$currentPageSearchResults = $col->slice(($currentPage – 1) * $perPage, $perPage)->all();
$popularCityEntries = new LengthAwarePaginator($currentPageSearchResults, count($col), $perPage);

$popularCityEntries->setPath($request->url());
$popularCityEntries->appends($request->except([‘page’]));
//end paginating popular cities array

return view(‘frontend.home’)
->with(‘popular_cities’,$popularCityEntries);
}
}

In View::
{!! $popular_cities->render() !!}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s