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 
//Using Twitter Boostrap up/down arrows
<th>Status
    <a href="{{action('WidgetsController@index', array('sort' => 'status', 'order' => 'asc'))}}">
        <i class="fa fa-chevron-up"></i>
    </a>
    <a href="{{action('WidgetsController@index', array('sort' => 'status', 'order' => 'desc'))}}">
        <i class="fa fa-chevron-down"></i>
    </a>
</th>

 

 

comments powered by Disqus