Tag Archives: columns

Laravel 4 Pagination with Column Sorting

Updated (4/24/2014) to address possible SQL injection attempt with $order and/or $sort input.

It took a little effort, but I finally got Laravel 4′s pagination class working with the ability to sort by column. Posted here so I don’t forget.

//Controller

$widgets = Widget::all();
$allowed_columns = ['column1', 'column2', 'column3'];
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'delivery_date';
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$widgets = $widgets->orderBy($sort, $order);
$widgets = $widgets->paginate(20);

//include $order and $sort when retrieving your layout/view
$this->layout->nest('content', 'widgets.index',array('widgets' => $widgets, 'sort' => $sort, 'order' => $order));

//View

//Display the pagination
//I tried using appends() first, but could not chain multiples
{{ $events->addQuery('order',$order)->addQuery('sort', $sort)->links() }}

//Column header
{{link_to_route('widgets.index','Name', array('sort' => 'name'))}}
//Using Twitter Boostrap up/down arrows
<a href="{{route($route, array('sort' => $sort, 'order' => 'asc'))}}">
<i class="icon-chevron-up"></i>
</a>
<a href="{{route($route, array('sort' => $sort, 'order' => 'desc'))}}">
<i class="icon-chevron-down"></i>
</a>