// Create custom method for Query Builder
<?php
//Usage Model::whereLike('name', ['mike', 'joe'])->get()
//Usage Model::whereLike('message.type', ['text', 'sms'])->get();
Builder::macro('whereLike', function ($attributes, $terms) {
$this->where(function ($query) use ($attributes, $terms) {
foreach (array_wrap($attributes) as $attribute) {
// If it's a single item, wrap the value in an array e.g. $term = [$term];
foreach (array_wrap($terms) as $term) {
// When whereLike contains a relationship.value, search the relationship value
$query->when(str_contains($attribute, '.'),
function ($query) use ($attribute, $term) {
[$relationName, $relationAttribute] = explode('.', $attribute);
// Validating if the relationship exists on the current query
$query->orWhereHas($relationName, function ($query) use ($relationAttribute, $term) {
$query->where($relationAttribute, 'LIKE', "%{$term}%");
});
},
// A fallback for when the string DOES not contain a relationship
function ($query) use ($attribute, $term) {
$query->orWhere($attribute, 'LIKE', "%{$term}%");
}
);
}
}
});
// Return the $query, so you can call other methods like ->get(), ->first(), ->where(), etc
return $this;
});
Query Builder Macros #laravel #queryBuilder #macros
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.