Skip to content

Instantly share code, notes, and snippets.

@rslhdyt
Created April 29, 2019 03:30
Show Gist options
  • Save rslhdyt/0abe7426e24584a3e0c6e9a2adb8a271 to your computer and use it in GitHub Desktop.
Save rslhdyt/0abe7426e24584a3e0c6e9a2adb8a271 to your computer and use it in GitHub Desktop.
[Searchable Traits] Simple searchable traits for laravel model #laravel #search #simpleSearch #traits
<?php
namespace App\Models;
use App\Models\Traits\Searchable;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
use Searchable;
private $searchable = [
'name',
'email'
];
....
}
<?php
namespace App\Models\Traits;
use Illuminate\Database\Eloquent\Builder;
trait Searchable
{
public function scopeSearch(Builder $query, $filter)
{
$query->when(!empty($filter['q']), function ($query) use ($filter) {
$keyword = $filter['q'];
$query->where(function (Builder $query) use ($keyword) {
foreach ($this->getSearchable() as $attribute) {
$query->orWhere($attribute, 'LIKE', "%{$keyword}%");
}
});
});
return $query;
}
public function getSearchable()
{
if (empty($this->searchable)) {
throw new \Exception('Please define searchable params');
}
return $this->searchable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment