0

I've started with Laravel for a week now and something bother me about the Query Builder and the when clause.

I'm using it like so:

$query->when($filters['full-time'] ?? false, fn ($query) =>
  $query->where('contract_type', JobPositionsEnum::class::FullTime)
);
      
$query->when($filters['location'] ?? false, fn ($query, $location) =>
  $query->where('location', 'like', '%' . $location . '%')
);

$query->when($filters['search'] ?? false, fn ($query, $params) => 
  $query->where('position', 'like', '%' . $params . '%')
    ->orWhere('description', 'like', '%' . $params . '%')
    ->orWhereHas('company', function ($query) use ($params) {
      $query->where('name', 'like', '%'.$params.'%');
    })
);

With this query I was hoping received an SQL request looking like this:

SELECT * FROM `jobs` 
WHERE `contract_type` = 'Full time' 
AND `location` like '%United%'
AND (`position` like '%S%' or `description` like '%S%' or EXISTS (SELECT * FROM `companies` WHERE `jobs`.`company_id` = `companies`.`id` and `name` like '%S%'))

But instead I'm receiving this:

SELECT * FROM `jobs` 
WHERE (
  `contract_type` = 'Full time' and 
  `location` like '%United%' and 
  `position` like '%S%' or `description` like '%S%' or EXISTS (
    SELECT * FROM 
      `companies` 
       WHERE `jobs`.`company_id` = `companies`.`id` 
       and `name` like '%S%'
   )
) 

I'm not sure to understand why the when group my query when I don't want to, did you know what I'm missing here ?

1
  • 3
    Move your OR queries into a subquery closure. Commented Sep 27, 2022 at 12:51

1 Answer 1

2

You should use an additional where to group the or conditions.

Your last when should look like this:

$query->when($filters['search'] ?? false, function ($query) use ($params) {
    $query->where(function ($query) use ($params) {
        $query->where('position', 'like', '%' . $params . '%')
            ->orWhere('description', 'like', '%' . $params . '%')
            ->orWhereHas('company', function ($query) use ($params) {
                $query->where('name', 'like', '%' . $params . '%');
            });
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ow.. I have to go deep about this ORM! I'm gonna read the doc carefully, thank you!

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.