26

I am trying to run a query using Eloquent the $vars['language'] is in lower case but the language column is not necessarily in lower case. How can i do this search using eloquent but still have the lower case in the query

Item::where('language', $vars['language'])

What i want to do is this even though i can't find anywhere how to do this

Item::where('LOWER(language)', $vars['language'])

so that they are both in lowercase and then i can get them to match.

Lpc_dark
  • 2,686
  • 7
  • 30
  • 47

3 Answers3

60

Use whereRaw with parameter binding to sanitize your whereRaw statement:

$term = strtolower($vars['language']);
Item::whereRaw('lower(language) like (?)',["%{$term}%"])->get();

Prev answer In some dabases you can use operator ilike in your where. For example

Item::where('language', 'ilike', $vars['language'])->get();

All available operators are:

protected $operators = array(
    '=', '<', '>', '<=', '>=', '<>', '!=',
    'like', 'not like', 'between', 'ilike',
    '&', '|', '^', '<<', '>>',
);

Edit: ilike is case-insensitive like.

Margus Pala
  • 7,848
  • 6
  • 36
  • 50
18

As per this post, a db-independent way to solve this would be:

Item::whereRaw('LOWER(language) = ?', [$vars['language']])->get();
igorsantos07
  • 4,149
  • 4
  • 40
  • 59
-1

The filter() collection method can be useful if you are trying to find a laravel-based solution :

// $this refers to an instance of an eloquent User Model
$name = 'BiLbo baGGings';    
return $this->contactInformation->filter(function($value, $key) use($name) { 
   if(strtolower($value->name) == strtolower($name)) {
       return $value;
   }
 });
Patrick.SE
  • 4,207
  • 5
  • 31
  • 44
  • 1
    This is not eagler-loading! where is the 'with' method? With $this->contactInformation you are loading to memory ALL the contacts infos, and then filtering. Hitting against memory instead of doing at a DB level is always the worst option :/ – dani24 Feb 23 '17 at 14:37
  • 1
    You are right, I edited out the parts that were incorrect about my answer to avoid confusing other readers. – Patrick.SE Feb 27 '17 at 17:18