Skip to content

Instantly share code, notes, and snippets.

@thepsion5
Last active August 29, 2015 13:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thepsion5/9099995 to your computer and use it in GitHub Desktop.
Save thepsion5/9099995 to your computer and use it in GitHub Desktop.
In example illustration of how to use a base query function to generate a filtered and sorted query without repeating code for each function.
<?php
public function index()
{
if(Input::get('sort')) {
$this->offices->sort(Input::get('sort'), Input::get('direction'));
}
$offices = $this->offices->all();
return View::make('app.offices.list', compact('offices'));
}
<?php
class DBOffice implements OfficeInterface
{
protected $offices;
protected $filter;
protected $defaultSort = array(
'type' => 'asc',
'name' => 'asc'
);
protected $currentSort = array();
protected $filterEnabled = true;
public function __construct(Office $offices, UserAccessFilterInterface $filter)
{
$this->offices = $offices;
$this->filter = $filter;
$this->currentSort = $this->defaultSort;
}
protected function getBaseQuery($sort = true)
{
$query = $this->offices->newQuery();
if($this->filterEnabled && !$this->filter->isAdmin()) {
$id = $this->filter->getCurrentUserId();
$query->where(function($q) use ($id) {
$q->where('user_id', $id)->orWhereNull('user_id');
});
}
if($sort) {
$this->addSortingToQuery($query);
}
return $query;
}
protected function addSortingToQuery($query)
{
foreach($this->currentSort as $field => $direction) {
$query->orderBy($field, $direction);
}
}
public function sort($field, $direction = 'asc')
{
array_unshift($this->currentSort, array($field => $direction));
return $this;
}
public function all($paginate = true)
{
$query = $this->getBaseQuery();
return ($paginate) ? $query->paginate($this->perPage) : $query->get();
}
public function findById($id)
{
return $this->getBaseQuery(false);
->whereId($id)
->first();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment