skip to Main Content

I get two parameters in my function as mobile and tel.
If they aren’t null, I want to search between my customers where it has a relation with my lead.

This is my query:

$lead = $this->query()
    ->with([
        'customer' => function ($query) use ($mobile, $tel) {
            $query->when($mobile != '', function ($query) use ($mobile) {
                return $query->where('mobile','=', $mobile);
            });

            $query->when($tel != '', function ($query) use ($tel) {
                return $query->where('tel','=', $tel);
            });
        },

    ])
    ->first();

However, it returns the wrong result.

2

Answers


  1. You can use if statements to check if $mobile and $tel are not null and then directly apply the where clauses to the $query.

    $lead = $this->query()->with('customer');
    
    if ($mobile !== null || $tel !== null) {
        $lead->whereHas('customer', function ($query) use ($mobile, $tel) {
            if ($mobile !== null) {
                $query->where('mobile', $mobile);
            }
    
            if ($tel !== null) {
                $query->where('tel', $tel);
            }
        });
    }
    
    $lead = $lead->first();
    
    Login or Signup to reply.
  2.     $lead = $this->query()->with(['customer' => function ($query) use 
          ($mobile,$tel) {
        if (!empty($mobile)) {
         $query->where('mobile', $mobile);
        }
    
       if (!empty($tel)) {
           $query->where('tel', $tel);
            }
        },
    ])->first();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search