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

Time:10-04

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

CodePudding user response:

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

CodePudding user response:

$values = array(
            "0" => ['Dell', 'hp'],
            "1" => ['Mac', 'linux', 'windows'],
            "2" => ['12.3', '12.5'],
            "3" => ['8 GB RAM'],
        );

        $val_arr = [];
    foreach ($values as $value) {
        foreach ($value as $item){
            $val_arr[] = $item;

        }
    }

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

you can do this just whereHas. You can look your array put 1 array and you can whereIn this array.

CodePudding user response:

Simple and sweet query:

use Illuminate\Support\Arr;

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

infinite/dynamic whereHas,

$x = BasicItem::query();

foreach($values as $value) {
    $x->whereHas('AttValue',
        fn($query) => $query->whereIn('attributeValue',$value)
    );
}

$x->get();
  • Related