0

I have a ModelA with columns: name, last_name, email

I want ModelA with the name Test to add an extra where on email

what I tried is the following

$model_a_res = A::when(
function($query){
    return $query->where('name','Test');
},
function ($query) { 
    $query->where('email', 'NOT LIKE', '%@test%');})
->first();

I want this second where to only run on A with column name = Test however, this is not working.

I tried it with user name Mike and his email [email protected] and he didn't appear in the result.

some data

id name email

1 Test [email protected] 
2 Test [email protected]
3 Mike [email protected]
4 Mike [email protected]

both 3 and 4 should be in the results 1 and 2 since they have name = Test will have another query which will check if he does have @test in his email if he does he will not be returned returned Rows are 2, 3, 4

5
  • can't understand what you asking for Commented Mar 8, 2024 at 10:26
  • Tell us what the inputs are + what you expect as output. Commented Mar 8, 2024 at 10:28
  • Add extra querying, extra where condition if this row has the column name = Test Commented Mar 8, 2024 at 10:28
  • This is an incomplete question.. Add more info to it Commented Mar 8, 2024 at 10:30
  • when() only executes the closure if the first argument is true. By that logic, your first parameter is not returning true. But we would need more information. Commented Mar 8, 2024 at 10:49

1 Answer 1

3

You can't use when() for this.

$model_a_res = A::where(function ($query) {
    $query->where('name', '!=', 'Test')
          ->orWhere(function ($query) {
              $query->where('name', '=', 'Test')
                    ->where('email', 'NOT LIKE', '%@test%');
          });
})->get();

Outputs

1 Test [email protected]  -  will skipp
2 Test [email protected] - added
3 Mike [email protected]  - added
4 Mike [email protected]  - added
Sign up to request clarification or add additional context in comments.

Comments

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.