Last active
August 29, 2015 13:56
-
-
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.
This file contains hidden or 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 | |
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')); | |
} |
This file contains hidden or 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 | |
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