Skip to content

Instantly share code, notes, and snippets.

@jaggy
Created August 6, 2019 01:40
Show Gist options
  • Save jaggy/5808f5834504b3adb4e87e188e3ae505 to your computer and use it in GitHub Desktop.
Save jaggy/5808f5834504b3adb4e87e188e3ae505 to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Database\Eloquent\Builder;
protected function registerWhereLikeMacro()
{
Builder::macro('whereLike', function ($attributes, $searchTerm = null) {
$this->where(function (Builder $query) use ($attributes, $searchTerm) {
foreach (array_wrap($attributes) as $attribute) {
$query->when(
str_contains($attribute, '.'),
function (Builder $query) use ($attribute, $searchTerm) {
[$relationName, $relationAttribute] = explode('.', $attribute);
$query->orWhereHas($relationName, function (Builder $query) use ($relationAttribute, $searchTerm) {
$query->where($relationAttribute, 'LIKE', "%{$searchTerm}%");
});
},
function (Builder $query) use ($attribute, $searchTerm) {
$table = $query->getModel()->getTable();
$query->orWhere("{$table}.{$attribute}", 'LIKE', "%{$searchTerm}%");
}
);
}
});
return $this;
});
}
<?php
namespace App\Concerns;
trait Searchable
{
public function scopeSearch($query, $search)
{
$query->whereLike($this->search, $search);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment