Skip to content

Instantly share code, notes, and snippets.

@vuthaihoc
Last active July 1, 2017 03:17
Show Gist options
  • Save vuthaihoc/9ff452a4df5addaaf1d36c987b84eb66 to your computer and use it in GitHub Desktop.
Save vuthaihoc/9ff452a4df5addaaf1d36c987b84eb66 to your computer and use it in GitHub Desktop.
Paginator sort link helper
<?php
/**
* Coding with 💚
* User: hocvt
* Date: 7/1/17
* Time: 08:55
*/
namespace App\Colombo;
use Illuminate\Contracts\Pagination\Paginator;
class PageHelper {
public static function sortLink(Paginator $paginator, $field, $title = '', $options = [], $asc = '&uarr;', $desc = '&darr;', $sort_key = 'sort'){
$sorting = \Request::query($sort_key);
$direct = false;
$sorting = preg_replace_callback('/(^|,)(\-?)(' . $field . ')($|,)/', function($matches) use(&$direct){
$direct = $matches[2] == "-" ? "" : "-";
return $matches[1] . $direct . $matches[3] . $matches[4];
}, $sorting);
if(array_get($options, "combined", false) === false){
$sorting = $direct . $field;
}
$title = $title ? $title : studly_case($field);
if($direct !== false){
$title .= " ";
$title .= $direct === '-' ? $asc : $desc;
}
$url = $paginator->appends([$sort_key => $sorting])->url(1);
return \Html::link($url, $title, $options, null, false);
}
public static function getSorting($default = [], $sort_key = 'sort', $only = []){
$sorting = [];
$sorted = explode(",", \Request::query($sort_key));
foreach ($sorted as $sort){
if(!$sort){break;}
if(strpos($sort, "-") === 0){
$sorting[substr($sort, 1)] = "desc";
}else{
$sorting[$sort] = "asc";
}
}
if($only){
$sorting = array_only($sorting, $only);
}
if(empty($sorting)){
$sorting = $default;
}
return $sorting;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment