Search code examples
mysqllaravelwherehas

Can I use for loop in laravel 9 WhereHas ? ( filter data )


I'm trying to build a filter on my data using laravel .. I have many to many relationships between the BasicItem model And AttValue Model and table Item_value between them.

this code works as what I want but I need it to be more dynamic depending on the user choice ex. this $value is what the user choices

$values = array(
        "0" => ['Dell','hp'],
        "1" => ['Mac' ,'linux','windows'],
        "2" => ['12.3' ,'12.5'],
        "3" => ['8 GB RAM'],
    );
    $x = BasicItem::whereHas('AttValue', function($query) use ($values) {
        $query->whereIn('attributeValue', $values["0"] );
    })
        ->WhereHas('AttValue', function($query) use ($values)  {
            $query->whereIn('attributeValue',$values["1"]);
        })
        ->WhereHas('AttValue', function($query) use ($values)  {
            $query->whereIn('attributeValue',$values["2"]);
        })
        ->WhereHas('AttValue', function($query) use ($values)  {
            $query->whereIn('attributeValue',$values["3"]);
        })
        ->get();

Now I want to Repeat the

->WhereHas('AttValue', function($query) use ($values)  {
    $query->whereIn('attributeValue',$values["$i"]); 

statement as many as the length of the array


Solution

  • If you want the query to work contextually the same, the best way is to do this:

    $x = BasicItem::query();
    foreach($values as $value) {
        $x->whereHas('AttValue', function($query) use ($value)  {
            $query->whereIn('attributeValue',$value);
        });
    }
    $x->get();
    

    Only results will show that have attributeValue in first array AND second array AND third array AND forth array and so on.

    EDIT: Changed solution to loop over whereHas in stead of whereIn