Skip to content

Instantly share code, notes, and snippets.

@lagbox
Last active February 26, 2016 11:11
Show Gist options
  • Save lagbox/1309002a208376087fb2 to your computer and use it in GitHub Desktop.
Save lagbox/1309002a208376087fb2 to your computer and use it in GitHub Desktop.
Old Searchable Trait for pulling fields from the schema
<?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