Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jpeterson579's avatar

Query db array field from form multi-checkbox array?

I can't wrap my mind around how this would be done or if its even the right way to go about it.

I have a database field called power that can have multiple values in it. Ex: Solar,Battery,Line So what I need to do if query the database based off of which checkboxes a user submits.

Form

<form class="productcomparison">
    <div>
        <p>Size/Width</p>
        Width Min <input name="width_min" value="">
        Width Max <input name="width_max" value=""><br>
    </div>
    <div>
        <p>Power Requirement</p>
        <input type="checkbox" name="chk_group[]" value="Solar" />Solar<br />
        <input type="checkbox" name="chk_group[]" value="Battery" />Battery<br />
        <input type="checkbox" name="chk_group[]" value="Rechargeable" />Rechargeable<br />
        <input type="checkbox" name="chk_group[]" value="Line" />Line<br />
    </div>
    <input name="submit" type="submit" value="Submit">
</form>

Controller.php

public function compare(Request $request)
{
    // 
    $req_width_min = $request->input('width_min'); 
    $req_width_max = $request->input('width_max');
    $power = $request->input('chk_group'); 
    
    $products = Product_Comparison::where('width_min', '<=', $req_width_min)
                                    ->whereRaw('width_max >= ' . $req_width_max)
                                    ->orderBy('created_at', 'asc')
                                    ->get();
    
    // Return Results to API
    return $request;
}
0 likes
3 replies
jpeterson579's avatar

Added

->where(function ($query) use($power_requirement) {
    for ($i = 0; $i < count($power_requirement ); $i++){
          $query->where('power_requirement', 'like',  '%' . $power_requirement [$i] .'%');
    }  
})

Seems to do the trick

jlrdw's avatar

Where is $power_requirement coming from, your variable is $power.

Cronix's avatar

In the db, what values do you actually have for the power_requirement column? I'm wondering why you're using like for it.

$req_width_min = $request->input('width_min'); 
$req_width_max = $request->input('width_max');
$power = $request->input('chk_group'); 
    
$query = Product_Comparison::where('width_min', '<=', $req_width_min)
    ->where('width_max', '>=', $req_width_max)
    ->orderBy('created_at', 'asc');

foreach ($power as $power_requirement) {
    $query->where('power_requirement', 'like',  '%' . $power_requirement .'%');
}

$products = $query->get();

return $products;

Also I think your where's are wrong for checking the dimensions. You're searching for less than min and greater than max. Shouldn't it be greater than min and less than max (between them)?

Please or to participate in this conversation.