Search code examples
phpmysqllaravel-5where-clausefluent

->where() clauses seem to be case sensitive


I have a query like so:

$profilesx->where('qZipCode', $location)->
                        orWhere('qCity', 'LIKE', '%'.$location.'%');

Where location is equal to belgrade, and the database column says Belgrade.

It seems to be case sensitive (using either = or LIKE) so if I search for Belgrade I get a result but if I search for belgrade I do not get any results.

How to make it case insensitive?


Solution

  • The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:

    source: http://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html

    What's actually happened is that the case sensitivity has been switched off (which is not neccassarily a bad thing). The solution is given in the next section of that document. Try something like

    orWhere('qCity', 'COLLATE latin1_general_cs LIKE', '%'.$location.'%');
    

    If laravel doesn't like it you will have to use a raw query or change the collation setting for the column.

    As a side note, try to avoid LIKE %something% queries if you can. Mysql cannot use an index for these sorts of queries and they generally tend to be slow on large tables because of it.