Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Last active July 24, 2018 20:36
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save stevebauman/adb4a7103c1b800867f3 to your computer and use it in GitHub Desktop.
Save stevebauman/adb4a7103c1b800867f3 to your computer and use it in GitHub Desktop.
/**
* Allows all columns on the current database table to be sorted through
* query scope
*
* @param type $query
* @param type $field
* @param type $sort
* @return object
*/
public function scopeSort($query, $field = NULL, $sort = NULL){
/*
* Make sure both the field and sort variables are present
*/
if($field && $sort){
/*
* Retrieve all column names for the current model table
*/
$columns = Schema::getColumnListing($this->table);
/*
* Make sure the field inputted is available on the current table
*/
if(in_array($field, $columns)){
/*
* Make sure the sort input is equal to asc or desc
*/
if($sort === 'asc' || $sort === 'desc'){
/*
* Return the query sorted
*/
return $query->orderBy($field, $sort);
}
}
} else{
/*
* Default order by created at field
*/
return $query->orderBy('created_at', 'desc');
}
@mdestafadilah
Copy link

can you explain more ? how to implement in > L5 .. thanks..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment