Laravel 5 pagination links - php

I have a laravel 5 application in which I`m trying to do a pagination for certain results (array of results not collection).
This is my code:
$paginator = new LengthAwarePaginator(
$l_aResponse['body'],
count($l_aResponse['body']),
'2',
Paginator::resolveCurrentPage(),
['path' => Paginator::resolveCurrentPath()]
);
return str_replace('/?', '?', $paginator->render());
My question is: is there a way to modify the way in which the "page" parameter is setup in the URL for pages? EG: I don't want this format: http://localsite/articles?page=3 but I want http://localsite/articles/3
I`ll appreciate any answer. Thanks!

The __construct() function of the LengthAwarePaginator class has a few parameters:
$items
$total
$perPage
$currentPage = null
array $options = []
As you can see the fourth parameter represents the current page.
So you can use a custom desired current page which has been retrieved from the last parameter from the url. An example would be:
// http://localsite/articles/3
$currentPage = ... // Get parameter from url
$paginator = new LengthAwarePaginator(
$l_aResponse['body'],
count($l_aResponse['body']),
'2',
$currentPage, // Current page as fourth parameter
['path' => Paginator::resolveCurrentPath()]
);
return str_replace('/?', '?', $paginator->render());
Have not tested this. Hope it helps :)

Related

Laravel Pagination the data not change with the render() in the blade

I have this problem, when i manually create a paginator in laravel for show 100 products, in the view the page displays the data and it is fine, but if i put a limit , example i want 10 element per page, he show the ten elements in the firs page, when i click in next the second page show me the same ten elements, the data don't changes , why?
Controller:
public function show()
{
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://www.mocky.io/v2/59bec4d926000046015261a7',
// You can set any number of default request options.
'timeout' => 2.0,
]);
$response = $client->request('GET', '');
$code = $response->getStatusCode()
$products = json_decode($response->getBody()->getContents());
}
$products = new Paginator($products, 10 ,
Paginator::resolveCurrentPage(),
['path' => Paginator::resolveCurrentPath()]);
return view('products/list', compact('products'));
}
View
#extends('layout.master')
#section('content')
<h2> Products</h2>
<ul>
#if($products)
#foreach($products as $product)
<li> {{ $product->name}} - {{ $product->value}}</li>
#endforeach
#endif
</ul>
{{$products->render()}}
#endsection
Example of Result with array of ten element , 3 per page
// this is a example with invented information.
array {0,1,2,3,4,5,6,7,8,9}
Page 1
0 - 0
1 - 1
2 - 2
Page 2 // the data dont change , why ?
0 - 0
1 - 1
2 - 2
No magic, paginators will call your controller function for every page. The request will have the pagination information in it. It is your job to actually select and slice the page. The paginator simply presents it... which is a big part of the work...
// DB::select returns an array, thus we have to build the paginator ourselves...
$comm = DB::select('select bla bla bla from comments where this and that...
order by approved ASC');
// this basically gets the request's page variable... or defaults to 1
$page = Paginator::resolveCurrentPage('page') ?: 1;
// Assume 15 items per page... so start index to slice our array
$startIndex = ($page - 1) * 15;
// Length aware paginator needs a total count of items... to paginate properly
$total = count($comm);
// Eliminate the non relevant items...
$results = array_slice($comm, $startIndex, 15);
$comments = new LengthAwarePaginator($results, $total, 15, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
return view('backend/comments', compact('comments'));
You need to add your page name (the name of the request param denoting the page number) like so:
$products = new Paginator($products, 10, null,
['path' => Paginator::resolveCurrentPath(),
'pageName' => 'page']);
I had the same problem, where the data was not changing. I solved it by passing a page number to my guzzle call. Whenever a link is clicked, a request is sent therefore, you can get the page number from the request object. Pass the page number to the guzzle call so that the page number changes. Hope It helps

Laravel LengthAwarePaginator returned data are not in single obejct

So i have made a custom pagination in laravel 5.4 using
Illuminate\Pagination\LengthAwarePaginator;
\Illuminate\Pagination\Paginator;
it returns the correct data and format during first request, but the 2nd request and others are not formatted same way as the first one.
So my question is how do I make the data to always return in a single object like the first request?
Below is my code on how I did my custom paginator and the console log.
$data = collect($playerMatchArr);
$result = new LengthAwarePaginator(
$data->forPage($page, 3),
$data->count(),
$limit,
$page
);
It is laravel json response which is doing this. I also spent couple of hours on it
finally managed to convert the response on the front end by receiving the response as
Object.values(response.data.data)
And finally i got the results
$data = collect($playerMatchArr);
$dataPerPage = $data->forPage($page, 3);
$dataPerPage = array_values($dataPerPage->toArray());
$dataPerPage = Collection::make($dataPerPage);
$result = new LengthAwarePaginator(
$dataPerPage,
$data->count(),
$limit,
$page
);

Use of manual pagination "$perPage" parameter

So I've been working on a pagination system that pulls data externally, after finally figuring out through trial and error I got the solution that works. While going through it something struck me as odd, as per the documentation $paginator = Paginator::make($items, $totalItems, $perPage);
I was wondering what's the actual use of the $perPage parameter? You would think that what ever number is specified would show that many items. But with manual pagination you have to limit the results that are passed into $items in order for it to work, otherwise you get the output of all items (as shown in code block below). Is manual pagination flawed? because if $perPage doesn't match the total number of items in the array $items it shows everything.
Example: Paginator::make( array('10xarray') ), 10, 2); it would show 5 pages with 2 items per page? where in reality it actually shows 10 items with 5 pages that all show the same 10 items.
<?php
class MainController extends BaseController {
public function library()
{
$this->layout->title = 'testing';
$this->layout->main = View::make('library/layout');
// Pagination data
$media = array(
array('title' => 'test'),
array('title' => 'test'),
array('title' => 'test'),
array('title' => 'test')
);
$perPage = 2;
$currentPage = Input::get('page', 1);
$pagedData = array_slice($media, ($currentPage - 1) * $perPage, $perPage);
$this->layout->main->paginated = Paginator::make($pagedData, count($media), $perPage);
if(Request::ajax()) {
return Response::json(
View::make(
'library/layout',
array('paginated' => $this->layout->main->paginated)
)->render()
);
}
}
}
it isn't flawed. it is intended behavior.
this manual paginator is just a container. nothing more, nothing less. how you implement it, is upon you.
without a LIMIT query, you can never do a pagination. when you use pagination(), laravel does the work under the hood. when you go for manual, you have to do it manually and get greater control.
why do you think it is called manual pagination in the first place?

How to show zend framework data grid data sorted by "date" as default?

How to show zend framework data grid data sorted by "date" as default?
When i get on the page, i wish to see data grid sorted by time as default, without getting params in URL like .../order/created_DESC/
$testimonials = new Application_Model_DbTable_Testimonials();
$source = new Bvb_Grid_Source_Zend_Table($testimonials);
Thanks.
I solved this by passing to datagrid $select instead of $object
$testimonials = new Application_Model_DbTable_Testimonials();
$source = new Bvb_Grid_Source_Zend_Table($testimonials);
is now
$testimonials = new Application_Model_DbTable_Testimonials();
$testimonials->setSortOrder('created');
$source = new Bvb_Grid_Source_Zend_Select($testimonials->getTestimonials());
It's hard to see what your class is doing since you didn't posted that one.
But when it's usess the fetchAll() function you can do two things:
Option 1
When there is an fetchAll()-call in the Grid class you can make this one:
$testimonialsTable->fetchAll(null, 'date'));
Option 2
You can re-write the fetchAll-Method in the Application_Model_DbTable_Testimonials class, when you make
public function fetchRow($where = null, $order = null, $offset = null)
{
if ($order===null) : $order='date'; endif;
return parent::fetchAll(where, $order, $offset)
}
Please notice in the last example fetchess always will be default sorted by the date-field.

Kohana 3 pagination

I'm really lost on how pagination works in kohana 3. Is there a good example of pagination in Kohana 3 anywhere?
// Get the total count of articles
$count = $this
->_profil
->articles
->count_all();
// Create the pagination object
$pagi = Pagination::factory(array(
'items_per_page' => 4,
'total_items' => $count,
));
// Find actual articles
$articles = $this->_profil
->articles
->join_categories()
->order_by('id','DESC')
->limit($pagi->items_per_page)
->offset($pagi->offset)
->find_all();
and then in the View, you just do
echo $pagi; // ofc, after passing the Pagination object to view
What happens here is Pagination class using it's View's __toString() magic method to render html needed to display pagination. All pagination params can be modified when creating the object (passing appropriate keys to the array passed to factory() method in our case).
Default key for pagination is "page" (query string), while you can modify that as well. Pagination also has a default config, which you can override by copying it to application/config folder.
Enjoy using it :)
In Kohana 3.1 pagination is not included. Download the module and put it in the modules folder. Enable the module in your application/bootstrap.php .This is my controller page. For further configuration copy the provided config file from modules/pagination/config/pagination.php to application/config/pagination.php
$per_page =2;
$page_num = $this->request->param('page', 1);
$offset = ($page_num - 1) * $per_page;
$view =View::factory('image/imagelist')->bind('page_links',$page_links)->bind('results', $results)->bind('pagination', $pagination);
// Get the total count of records in the database
$userid = Auth::instance()->get_user()->pk();
$count=ORM::factory('user_image')->where('app_userid','=',$userid)->count_all();
// Create an instance of Pagination class and set values
$pagination = Pagination::factory(array(
'total_items' => $count,
'current_page' => array('source' => 'image/imagelist', 'key' => 'page'),
'items_per_page' => $per_page,
'offset' => $offset,
'view' => 'pagination/basic'
));
// Load specific results for current page
$results = DB::select()->from('user_images')
->where('app_userid','=',$userid)
->order_by('image_id','ASC')
->limit($pagination->items_per_page)
->offset($pagination->offset)->execute();
$page_links = $pagination;
$this->template->content=$view->render();
You may get error ErrorException [ Notice ]: Undefined property: Request::$uri. in the pagination class (module). In order to fix fix it
Use Request::current()->uri() instead of Request::current()->uri
You can find some decent docs in the unofficial Kohana wiki.

Categories