1

In following pagination query i added the sorting code with OrderBy method but gives an error on first time page reload because there is no sort and order field is set there. how can i condition it set if exist or set null or else.

->select(array(
                'to_jobs.rec_id',
                'to_jobs.contarct_code',
                'to_jobs.job_num',
                'to_sites.site_name',
                'to_sites.postcode',
                'to_sites.site_id' 
                ))
            ->orderBy(Request::get('sort'), Request::get('order'))
            ->leftjoin('to_sites', 'to_jobs.fk_site_id', '=', 'to_sites.site_id')
            ->paginate(10);
Alfiza malek
  • 994
  • 1
  • 14
  • 36
  • Surely you will need to sort the results in the same order EVERY time you run the pagination code, or you will end up loosing rows or presenting some on more than one page – RiggsFolly Dec 09 '16 at 11:55

2 Answers2

0

If you're using Eloquent, you can use local scope.

For query builder query, you can try to use when():

->when(request()->has('sort'), function ($q) {
    return $q->orderBy(request()->sort, request()->order);
})
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

You can simply use if statement to check sort input and then build your pagination.

Try this.

$query->select(array(
        'to_jobs.rec_id',
        'to_jobs.contarct_code',
        'to_jobs.job_num',
        'to_sites.site_name',
        'to_sites.postcode',
        'to_sites.site_id'
    ))
    ->leftjoin('to_sites', 'to_jobs.fk_site_id', '=', 'to_sites.site_id');
if (Request::has('sort'))
{
    $query->orderBy(Request::get('sort'), Request::get('order'));
}
$query->paginate(10);


Reference:
Community
  • 1
  • 1
Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97