0

I want to gather all the tags' ids whose names are in an array. For that I'm using whereIn like so:

$tags = Category::whereIn('name', $tag_names)->pluck('id')->toArray(); 

I works perfectly but I doesn't have an option (that I know of) that makes the operator of whereIn case-insentive.

$tag_names are an array of tag names which have arbitrary casing.

'name' is the column that holds the name of the tag in the database and has specific casing that may not match the one in $tag_names.

My postgresql schema for the Categorytable is:

CREATE TABLE categories (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    description TEXT,
    num_posts INTEGER DEFAULT 0 NOT NULL
);
3
  • You could try whereIn('LCASE(name)',strtolower($tag_names)) Commented May 26, 2018 at 17:58
  • @vivek_23 Firstly, the second argument should be array_map('strtolower', $tag_names). Secondly, the first argument throws a Postgresql error, even if I try it with lower instead of LCASE. Thank you anyway for trying to help! Commented May 26, 2018 at 18:28
  • I apologize, I need some coffee. By the way, I checked this on my machine and it does work fine. Commented May 26, 2018 at 19:07

1 Answer 1

2

The array in the search makes it a little more difficult. If you want a non-case-sensitive result, you can just force them both to one case:

$tags = Category::whereIn( 'LCASE(name)' ,  strtolower($tag_names) )

Alternately, if you want to match without forcing the case, you might try:

$query = Category::with('tags');
foreach ($tag_names as $tag) {
     $query->whereHas('tag', function($q) use ($tag) {
         $q->where('name', 'ilike', $tag);
     });
 }
 $query->get();
Sign up to request clarification or add additional context in comments.

2 Comments

I would really like an approach like the first one but it doesn't work. Firstly, the second argument should be array_map('strtolower', $tag_names). Secondly, the first argument throws a Postgresql error, even if I try it with lower instead of LCASE. Thank you anyway for trying to help!
You have to use a raw expression: whereIn(DB::raw('lower(name)'),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.