I'm working on a Laravel API with a MongoDB database using jenssegers/laravel-mongodb.
I'm trying to make a filter to get some particular data using a regex. In the tutorial for this plugin I found this:
User::where('name', 'regex', new MongoRegex("/.*doe/i"))->get();
So my code looks like this:
School::where('name', 'regex', new MongoRegex("/haags/i"))->get();
But the result is empty. When I output the query it looks like this:
db.schools.find({"name":{"$regex":{"regex":"haags","flags":"i"}}})
And when I use that query in the console it says:
error: {
"$err" : "Can't canonicalize query: BadValue $regex has to be a string",
"code" : 17287
}
I also tried:
School::where('name', 'regexp', "/haags/i")->get();
But that gave me this query:
db.schools.find({"name":{"$regex":"\/haag\/i"}})
which apparently escapes the forward slash and makes the regex invalid. And besides that, a regex should not be between quotes or it should be something like this (found in the MongoDB manual):
db.products.find( { description: { $regex: /^S/, $options: 'm' } } )
So there is a problem in the conversion to MongoDB query or I'm doing something wrong. Can someone please tell me what it is?