skip to Main Content

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search