Last active
February 26, 2016 11:11
-
-
Save lagbox/1309002a208376087fb2 to your computer and use it in GitHub Desktop.
Old Searchable Trait for pulling fields from the schema
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 | |
/* | |
Model trait | |
Uses: | |
Model::getDates() // to not search dates | |
Model::getHidden() // to not search hidden fields | |
Optional: | |
var $searchable = [] // set which fields you want searchable | |
var $unsearchable = [] // set which fields should be unsearchable | |
*/ | |
trait SearchableTrait | |
{ | |
public function getSearchable() | |
{ | |
// if we already grabbed the searchable just return them | |
if (isset($this->_searchable)) { | |
return $this->_searchable; | |
} | |
// if searchable was set on the model and not empty | |
if (! empty($this->searchable)) { | |
return $this->_searchable = $this->searchable; | |
} | |
// pull the column names from the schema | |
$cols = $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable()); | |
// if unsearchable was set and not empty, remove the unsearchable columns | |
if (! empty($this->unsearchable)) { | |
$cols = array_diff($cols, $this->unsearchable); | |
} | |
// dont search hidden fields or dates, set _searchable for later use | |
return $this->_searchable = array_diff($cols, $this->getDates(), $this->getHidden()); | |
} | |
public function scopeSearch($query, $s) | |
{ | |
$searchable = $this->getSearchable(); | |
$query->where(function ($q) use ($searchable, $s) { | |
foreach ($searchable as $field) { | |
$q->orWhere($field, 'LIKE', "%$s%"); | |
} | |
}); | |
return $query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment