Skip to content

[12.x] Add Str::escapeLike() and escape parameter to whereLike #59157

Open
SanderMuller wants to merge 3 commits intolaravel:12.xfrom
SanderMuller:12.x
Open

[12.x] Add Str::escapeLike() and escape parameter to whereLike #59157
SanderMuller wants to merge 3 commits intolaravel:12.xfrom
SanderMuller:12.x

Conversation

@SanderMuller
Copy link
Contributor

Summary

  • Adds Str::escapeLike() (and Stringable::escapeLike()) to escape %, _, and \ characters in LIKE query values
  • Adds an escape parameter to whereLike, orWhereLike, whereNotLike, and orWhereNotLike

whereLike was added to simplify LIKE queries, but it doesn't protect against the most common mistake: user input containing % or _. Adding escape: true makes the safe path the easy path, while Str::escapeLike() serves advanced use cases.

Usage

The key design goal: adding escape: true to an existing whereLike call should just work.

// Before: user input with % or _ breaks the query
$query->whereLike('title', '%'.$search.'%');

// After: just add escape: true, nothing else changes
$query->whereLike('title', '%'.$search.'%', escape: true);

When escape: true, leading and trailing % wildcards are preserved and everything in between is escaped. This means all common patterns work naturally:

// Contains
$query->whereLike('title', '%'.$search.'%', escape: true);

// Starts with
$query->whereLike('title', $search.'%', escape: true);

// Ends with
$query->whereLike('title', '%'.$search, escape: true);

// Exact LIKE match (no wildcards)
$query->whereLike('title', $search, escape: true);

Str::escapeLike() is also available standalone for manual composition:

// Complex patterns
$query->whereLike('path', Str::escapeLike($dir).'/%');

// Edge case: value literally ends with %
$query->whereLike('name', Str::escapeLike('50%'));

Design decisions

  • Opt-in, not default: fully non-breaking, no existing code changes behavior
  • Preserves boundary % wildcards: so escape: true is a drop-in addition to existing queries without restructuring the value
  • On Str, not DB: escapeLike is a string operation, usable outside of query building
  • Edge case: if user input itself starts or ends with a literal %, the boundary preservation can't distinguish it from an intentional wildcard. For this rare case, use Str::escapeLike() directly. In practice, this almost never matters, and if you need an exact match of a value containing %, you'd typically use where() instead of whereLike()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant