Created
April 29, 2019 03:30
-
-
Save rslhdyt/0abe7426e24584a3e0c6e9a2adb8a271 to your computer and use it in GitHub Desktop.
[Searchable Traits] Simple searchable traits for laravel model #laravel #search #simpleSearch #traits
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 | |
namespace App\Models; | |
use App\Models\Traits\Searchable; | |
use Illuminate\Database\Eloquent\Model; | |
class Customer extends Model | |
{ | |
use Searchable; | |
private $searchable = [ | |
'name', | |
'email' | |
]; | |
.... | |
} |
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 | |
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