Last active
August 29, 2015 14:16
-
-
Save derrekbertrand/23157faf0aa982fd71b6 to your computer and use it in GitHub Desktop.
Laravel 4.2 Controller for responding to bs_grid AJAX requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Usage: Point bs_grid to GridController@postModelName (make sure route is defined for the action) | |
* Whitelist models by making appropriate public methods. | |
* Controller will respond to basic use and sorting appropriately. | |
*/ | |
class GridController extends BaseController { | |
public function __construct() | |
{ | |
//It would be wise to define some sensible filters | |
//...unless you like to be mined | |
//$this->beforeFilter('auth'); | |
} | |
//In this way we create a white list of models... | |
//You probably do not want all models accessed this way | |
public function postUser() | |
{ | |
return $this->BSGrid('User'); | |
} | |
public function postPhoto() | |
{ | |
return $this->BSGrid('Photo'); | |
} | |
//this takes a Laravel Model name and returns the JSON | |
//that bs_grid expects | |
//currently handles sorting and pagination appropriately | |
//TODO: respond to filter | |
//TODO: actually pay attention to the fields | |
public function BSGrid($model) | |
{ | |
//default required data | |
$data = array( | |
'total_rows' => null, | |
'page_data' => null, | |
'error' => null, | |
'filter_error' => array(), | |
'debug_message' => array() | |
); | |
try { | |
//get the proper number of rows, paginated | |
$request = $model::take(Input::get('rows_per_page')) | |
->skip((Input::get('page_num')-1)*Input::get('rows_per_page')); | |
//now specify sorting, etc | |
foreach(is_array(Input::get('sorting')) ? Input::get('sorting') : [] as $sort) | |
{ | |
if($sort['order'] == 'ascending') | |
$request->orderBy($sort['field'], 'ASC'); | |
if($sort['order'] == 'descending') | |
$request->orderBy($sort['field'], 'DESC'); | |
} | |
//get data and rows | |
$data['page_data'] = $request->get()->toArray(); | |
$data['total_rows'] = $model::all()->count(); | |
} | |
catch (Exception $e) { | |
$data['error'] = 'Server error in GridController.'; | |
$data['debug_message'][] = $e->getMessage(); | |
} | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment