lundi 11 février 2019

Laravel LengthAwarePagination

I am working with laravel's LengthAwarePaginator Class. My problem is that I cannot use

$users = DB::table('users')->paginate(15);

or in other words,larvel's querybuilder or eloquent results. The reason is I have provided user with a frontend where they can create queries dynamically that can as simple as a select query and can be as complicated as queries with multiple joins etc. So I am left with only option of using LengthAwarePaginator. Here is what I have done do far

private function queryWithPagination($queryString,$path,$fieldName = '',$sortOrder = '',$perPage = 100){


    $queryString = str_replace(''',"'",$queryString);
    $queryString = str_replace('**',"",$queryString);

    if(!empty($fieldName) && !empty($sortOrder)){
        $queryString .= " ORDER BY '{$fieldName}' {$sortOrder}";
    }

    $currentPage = LengthAwarePaginator::resolveCurrentPage();  
    $limit = $perPage +1;   // to have pagination links clickable i.e next,previous buttons   
    $queryString.= " LIMIT {$limit}";        

    if($currentPage == 1){
        $queryString.= " OFFSET 0";
    }
    else{
        $offset = ($currentPage-1)*$perPage;
        $queryString.= " OFFSET {$offset}";
    }

    $path = preg_replace('/&page(=[^&]*)?|^page(=[^&]*)?&?/','', $path);

    $result = DB::connection('database')->select($queryString);

    $collection = new Collection($result);
    //$currentPageSearchResults = $collection->slice(($currentPage - 1) * $perPage, $perPage)->all();
    $entries = new LengthAwarePaginator($collection, count($collection), $perPage);
    $entries->setPath($path);
    //dd($queryString,$result);
    dd($entries);
    return $entries;

}

As you can see I append LIMIT and OFFSET in the query otherwise, for complex queries the load time was getting greater resulting in bad user experience. The problem with current set up is that the last page is always set to 2 and when I get to second page I cannot browse more results i.e cases where records returned were more than 500 I can still only browse upto page 2. How do I fix this issue where by using limit offset I can still keep browsing all the results until I get to the last page and then disable the pagination links?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire