Articles::paginate(10)
This code will return the 1st 10 articles, what if I want to return the next 10 articles with route? For example the url mypage.com/articles/2 will return the 2nd 10 articles from database.
This is so far what I have:
Route:
Route::get('articles/{page_number}', 'Controller#getArticles')
Controller:
public function getArticles($page_num)
{
$perPage = 10;
Articles::getPaginator()->setCurrentPage($page_num);
$articles = Articles::paginate($perPage);
return $articles;
}
Can I have something like Articles::pageNumber($page_number)->paginate($perPage);?
Laravel paginator automatically checks for the the value of page in query string and uses it to paginate the results. The result also automatically generates the next and previous links to help you add them directly. You don't need to change anything to make it work.
In your case you can use $articles->links() in your view to generate the pagination navigation buttons. But if you want to manually set the page then you can do this.
$articles = Articles::paginate(5, ['*'], 'page', $pageNumber);
The default paginate method takes the following parameters.
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null);
The default convention is
mypage.com/articles?page=2
mypage.com/articles?page=3
Also if you use $articles->links() to generate the navigation button, you can also customize the css.
Check out https://laravel.com/docs/5.4/pagination for more info
$results= DB::table('subscribers')->select('id', 'name', 'email')->paginate(20);
$results->count();
$results->currentPage();
$results->firstItem();
$results->hasMorePages();
$results->lastItem();
$results->lastPage(); (Not available when using simplePaginate)
$results->nextPageUrl();
$results->perPage();
$results->previousPageUrl();
$results->total(); (Not available when using simplePaginate)
$results->url($page);
Related
I am trying to create infinite scroll in laravel for that I am using default pagination and it is working fine but I want a pagination to use filtering.
public function infinite_scroll(Request $request)
{
$key = $request->input('key');
$group_name = $request->input('groupname');
$wachat = Wechat::where('key', '=', $key)->where('groupName', '=', $group_name)->orderBy('id', 'DESC')->paginate(2);
$this->response['values'] = $wachat;
$this->response['key'] = $key;
return response()->json(
$this->response
);
}
I am using this code and it is giving me this url in next url:
next_page_url: "http://localhost:8888/kc/kyo-webservice/public/api/v1/wechatinfinite?page=2"
But I want a filtering based on key and groupname for example when I pass a param groupname and key it should give me values.
When I am trying to get next page url it is not working I want my result for pagination based on my filter it should give me next page url like this:
next_page_url: "http://localhost:8888/kc/kyo-webservice/public/api/v1/wechatinfinite??key=smg1np1f77&groupname=group&page=2"
And it should give me result based on my filters.
used appends() pagination method here
Appending To Pagination Links
You may append to the query string of pagination links using the
appends method. For example, to append sort=votes to each pagination
link, you should make the following call to appends:
$wachat->appends(['key'=> $key,'groupname' => $group_name]);
in your controller do like that
public function infinite_scroll(Request $request)
{
$key = $request->input('key');
$group_name = $request->input('groupname');
$wachat = Wechat::where('key', '=', $key)->where('groupName', '=', $group_name)->orderBy('id', 'DESC')->paginate(2);
$wachat->appends(['key'=> $key,'groupname' => $group_name]);
$this->response['values'] = $wachat;
$this->response['key'] = $key;
return response()->json(
$this->response
);
}
I am on Laravel Framework version 5.1.45 (LTS).
One club can have many events. I am trying to list all the events, group them by year and show one page per year.
According to my Laravel version documentation "Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually."
Here is my attempt to create the paginator manually and it seems to do the job:
public function index()
{
$page = Paginator::resolveCurrentPage() - 1;
$perPage = 1;
$events = new Paginator(Event::orderBy('date', 'desc')->groupBy(DB::raw('YEAR(date)'))->skip(($page - 1) * $perPage)->take($perPage + 1)->get(), $perPage, $page);
$events->setPath(['events/events']);
return view('events.index', ['events' => $events]);
}
And here is how I try to display the links at the bottom of the page.
{!! $events->render() !!}
If I remove the render bit, the page is displayed, albeit with no links. I can even go to the next page (year 2016) adding manually ?page=2 at the end of the url in my browser.
But if I leave the render bit in the index page, I get ErrorException in AbstractPaginator.php line 130: Array to string conversion.
What am I doing wrong?
Hope this snippet can help
public function index(Request $request)
{
$posts = Post::all()
->paginate($request->get('per_page', 25));
$grouped_by_date = $posts->mapToGroups(function ($post) {
return [$post->published_date => $post];
});
$posts_by_date = $posts->setCollection($grouped_by_date);
return view('posts.index', compact('posts_by_date'));
}
Basically redefine the collection with the grouped collection.
Having problems getting my pagination to work in Laravel 5.2 I use a foreach to generate a list of objects where each object has a certain ranking. (competition)
The first query I used was this one:
$goedeDoelen = GoedDoel::orderBy('punten', 'desc')->simplePaginate(5);
This worked pretty ok, only problem was that my ranking would reset everything I would go to a different page.
Example: Page 1 has objects from rank 1 - 5, page 2 should have ranks 6-10. By using the first Paginate method, the second page would have objects starting from 1 again.
I have tried to work around this by adding the ranking as an extra attribute to my Eloquent collections.
$ranking = GoedDoel::orderBy('punten', 'desc')->get();
foreach($ranking as $key => $item) {
$item->ranking = $key+1;
}
After that I tried to use ->simplePaginate() on my updated collection. This gave an error.
I have created a custom Paginator.
$goedeDoelen = new Paginator($ranking, 5);
This isn't working as intended. When I go to my second page, the URL messes up and goes to another view.
How can I make sure the Paginator knows what my current URL is to which it has to apply the ?page=2
You need to use the paginate() method.
$goedeDoelen = GoedDoel::orderBy('punten', 'desc')->paginate(5);
{!! $goedeDoelen->links() !!}
The following Code illustrates manual pagination in Laravel
Sample Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use App\Models\UserRechargeDetails;
class PaginateController extends Controller
{
//
public function index(Request $request)
{
$user_1 = new UserRechargeDetails;
// Get records from Database
$items = $user_1->all();
// Store records in an array
$records = [];
$i = 0;
foreach($items as $item)
{
$records[$i][0] = $item->user_name;
$records[$i][1] = $item->rech_mobile;
$i++;
}
// Current page for pagination
$page = $request->page;
// Manually slice array of product to display on page
$perPage = 2;
$offset = ($page-1) * $perPage;
$data = array_slice($records, $offset, $perPage);
// Your pagination
$final_data = new Paginator($data, count($records), $perPage, $page, ['path' => $request->url(),'query' => $request->query(),]);
/*
For Display links, you may add it in view page
{{ $data->links('pagination::bootstrap-4') }}
*/
return view('admin.pagination_new', ['data' => $final_data, 'j' => 1]);
}
}
I am trying to make a paginator in Symfony and this is how my code looks like:
Controller class:
class MovieDisplayController extends Controller
{
public function showAction()
{
//Records:
//$movies = $this->getDoctrine()->getEntityManager()->getRepository('AppBundle:Movie')->FindAll();
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT m
FROM AppBundle:Movie m'
)->setMaxResults(5)->setFirstResult(0);
$movies = $query->getResult();
//$resultAmount = $query->getResult()-count();
//Pagination:
$filterVariables = "";
$currentPage = (isset($_GET['page'])) ? $_GET['page'] : 1;
$totalPages = /*Example: */20; //something like: $this->count($movies) / $recordsPerPage
return $this->render('movies/index.html.twig', array(
'movies' => $movies,
'filtervariables' => $filterVariables,
'page' => $currentPage,
'totalPages' => $totalPages
));
}
}
This code works perfectly fine, however I want to make my paginator work and I have to pass some GET variables in the LIMIT part of a query (at least that is what I found out after doing some searching).
First of all, let me ask if any of you would know, the use of the GET variables in the "pagination" part of the class, would that be the proper way in Symfony to call those? I have seen something like: $foo = $request->query->get('page'); but that does not seem to return anything (or at least not the same as the $_GET['page'] variable), or am I trying to do something that is not possible (anymore)?
(Also I do not wish to make use of routing for this)
Secondly I would like to know if it is possible (or how) to count the amount of results I would get by using $movies = $query->getResult().
If anyone has any tips or advice for me to optimize my code and make it working, I would gladly want to know.
Edit: My pagination works fine now, if there should be any tweaks to make it even work more perfectly, feel free to add a comment or an answer if it's an important change. (Code used)
Thanks in advance.
GET and SET variables within symfony
There are several possibilities how to pass variables to controller. The simplest will be to use the routing.
/**
* #Route("something/{page}/{limit}", defaults={"page" = 1, "limit" = 10}, name="show_action")
*/
public function showAction($page, $limit)
{
}
Then you will be able to use $page and $limit directly inside your controller.
If you don't want to use routing you may also use session instead:
public function showAction(Request $request)
{
$this->get('session')->get("page");
$this->get('session')->get("limit");
}
Counting records
You may count your sql records using DQL:
$query = $this->createQueryBuilder()
->from('Movie', 'f')
->getQuery();
$total = $query->select('COUNT(f)')
->getQuery()
->getSingleScalarResult();
I was trying to list using pagination in Codeigniter. I was willing to use sorting in the list by using jquery ajax. It works perfectly for first page of pagination. I could do ascending and descending sorting in that page. But when i click on other page. It does not work.
What could be the problem. Can any one suggest me??
Thanks in advance.
This is the code for my controller
function listData(){
$this->clear_sample_id_catche();
$out=$this->Mgeneral->listData();
$per_page = 10;
$total = $this->Mgeneral->countData();
$data = $this->Mgeneral->listData($per_page, $this->uri->segment(3));
$base_url = site_url('general/listData');
$config['base_url'] = $base_url;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['uri_segment'] = '3';
$this->pagination->initialize($config);
$data=array('body'=>'list','out'=>$data);
$this->load->view('template',$data);
}
This is for my model
function listData($limit = NULL, $offset = NULL)
{
$this->db->limit($limit, $offset);
$data=array();
$q=$this->db->get('tbl_sample_id');
if($q->num_rows()>0)
{ $data=$q->result_array();
return $data;
}
}
and i have use ajax as
<script type="text/javascript">
$(document).ready(function(){
$("#internal").click(function(){
$.ajax({url:"general/listData_internal_ascending",success:function(result){
$("body").html(result);
}});
});
});
Thank you
Pagination uses the Limit and the Offset parameters when making the database calls. If you're using pagination, then clicking the page links will pass back the Offset. If this is working for you so far, then all you need to do is make sure that you keep the Sort parameter somewhere in your page.
If your controller method is checking for the GET variable to find the offset for the pagination, you need to make sure that the method also knows which field to sort by. I personally store it in flashdata.
So in your controller methood, before the db call:
$SortColumn = $this->session->flashdata('SORT_BY');
If there's no Sort saved there, then it returns false, so you can check for that when adding your $db->order_by() method. If there is something there, then you can sort appropriately.
Then right at the bottom of the method before the view gets loaded, set the Sort back to flashdata so the next time the method is called (on next page request), it has the Sort field to work with again.
$this->session->set_flashdata('SORT', $SortColumn);
Sorry I don't have any full code examples, as I use PHP-ActiveRecord instead of the CI built-in activerecord library.
You function should look like this
function listData($limit = NULL, $offset = NULL)
{
$this->db->limit($limit, $offset);
$this->db->order_by('id');
$q = $this->db->get('tbl_sample_id');
if($q->num_rows()>0)
{
return $q->result_array();
}
}
I can suggest you to pass sorting parameters in your ajax call of pagination . that could be the problem.