Hi Everyone
Today we will going to learn, How to create pagination using array instead of an object.
Generally, In Laravel we use simplePaginate() or paginate() functions to paginate. But these function by default work on if we have an object.
Some time we need to pass an array in blade template. So how can we do pagination on array. To do this we have to use following code.
Firstly include these two lines in our controller where we want to do pagination.
Then make a function like below in same controller.
In above function first parameter is an array whom we want to paginate and second parameter is number of item we want to show per page.
Now lets see how we can use it.
In the controller suppose we have another function, from where we want to sent data to view.
In blade template we have to use following line of code to show paging.
Hope this will help someone.
Thanks
Today we will going to learn, How to create pagination using array instead of an object.
Generally, In Laravel we use simplePaginate() or paginate() functions to paginate. But these function by default work on if we have an object.
Some time we need to pass an array in blade template. So how can we do pagination on array. To do this we have to use following code.
Firstly include these two lines in our controller where we want to do pagination.
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
Then make a function like below in same controller.
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()));
}
In above function first parameter is an array whom we want to paginate and second parameter is number of item we want to show per page.
Now lets see how we can use it.
In the controller suppose we have another function, from where we want to sent data to view.
public function getData($){
$getData = \App\ModelName::all();
$dataArray = array();
$i=0;
foreach($getData as $data){
$dataArray[$i]['id'] = $data->id;
$i++;
}
$data = array('data' => $this->paginate($dataArray,'15'));
return view("viewName", $data);
}
In blade template we have to use following line of code to show paging.
{!! $data->render() !!}
Hope this will help someone.
Thanks
Is need some routes? Laravel say's me: The GET method is not supported for this route. Supported methods: POST.
ReplyDeleteWhen I try to go next page.