James Haskell
James Haskell

Reputation: 113

Laravel Eloquent Multiple 'WHERE NOT LIKE' Statements

I am trying to filter a users list to remove any test accounts with certain email extensions.

My query:

User::where('email', 'NOT LIKE', '%test.com')
    ->where('email', 'NOT LIKE', '%test1.com')
    ->where('email', 'NOT LIKE', '%test2.com')
    ->where('email', 'NOT LIKE', '%test3.com')

I'm wondering if there's a better way to write this in one statement like whereNotIn but that doesn't seem to work. I'm looking for something like this:

User::whereNotLike('email', [
    '%test.com',
    '%test1.com',
    '%test2.com',
    '%test3.com',
]);

Upvotes: 3

Views: 1093

Answers (1)

IGP
IGP

Reputation: 15849

The only way to achieve what you want is to use regular expressions in the query.

Here's one that should catch all your use cases.

$users = User::whereRaw("email NOT REGEXP '?'", ['test[0-9]*.com$'])->get();

Here's another one using your specific values.

$endsWith = [
    'test.com$',
    'test1.com$',
    'test2.com$',
    'test3.com$',
];

$users = User::whereRaw("email NOT REGEXP '?'", [implode('|', $endsWith])->get();

Upvotes: 4

Related Questions