Skip to content

Instantly share code, notes, and snippets.

@gms8994
Created November 4, 2019 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gms8994/6943b2cd44e43f444992ede566bcbb62 to your computer and use it in GitHub Desktop.
Save gms8994/6943b2cd44e43f444992ede566bcbb62 to your computer and use it in GitHub Desktop.
Query builder macro to replace one where clause with another
/**
* Replaces a where clause in a Builder with another where clause
*/
Builder::macro('replaceWhere', function (Builder $passedQuery, \Closure $howToGetValue) {
$wheres = $passedQuery->wheres;
$query = $passedQuery->cloneWithout([ 'wheres' ]);
$bindings = [];
foreach ($wheres as &$where) {
$where = array_merge($where, $howToGetValue($where));
$bindings[] = $where['values'] ?? $where['value'];
}
$query->wheres = $wheres;
$query->setBindings(Arr::flatten($bindings), 'where');
return $query;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment