Friday, March 11, 2016

Create pagination using an array instead of object in Laravel

Create pagination using an array instead of object in Laravel:

In Laravel 5 we can use pagination by using simplePaginate() or paginate() functions. These functions works in case of object.

If we want to direct use this pagination in any array then we have to use the following code.

Firstly include these two lines:

use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;


After that use this:


    public function indexTransaction()
    {
        $fullDetail = array();
        $user = new User();
        $txnDetail = Transaction::getAllDetail();
        foreach ($txnDetail as $k => $v) {
            $fullDetail[$k]['admin_amt'] = $v->admin_amt;
            $fullDetail[$k]['publisher_amt'] = $v->publisher_amt;
            $fullDetail[$k]['reseller_amt'] = $v->reseller_amt;
            $fullDetail[$k]['pub_sent_status'] = $v->pub_sent_status;
            $fullDetail[$k]['reseller_sent_status'] = $v->reseller_sent_status;
        }
        $finalDetail = $this->paginate($fullDetail, '20');
        return view('admin.transaction')->with('txnDetail', $finalDetail);
    }

    public function paginate($items, $perPage)
    {
        $pageStart = \Request::get('page', 1);
        $offSet = ($pageStart * $perPage) - $perPage;
        $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
        return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
    }



This will create a pagination in case of array.

Thanks

2 comments:

  1. Its not working, i have a json response array,
    $loadData = $data['key1']['key2']['key3'];

    $paginate = $this->paginate($loadData, '20');

    It gives me and error saying "Call to a member function links() on null" please help me, im using laravel 5.4

    ReplyDelete
  2. Thank you very much for that answer of PAGINACIÓN it helped me a lot

    ReplyDelete