Rana
Rana

Reputation: 53

How to fetch data from table appending various queries in Laravel 5.2?

I'm trying to append various different queries for my filter but the problem here is my orWhere condition is working abnormally and giving me results irrespective of my where condition.

I'm adding my controller below:

public function earringsFilter(Request $request)
{
    if($request->isMethod('post')) {
        $data = array_filter($request->all());
        $filter = $data['filter'];
        $jewelleryEarringsData = Jwellery::select('id','name','price','msrp','metal_type','image_url','total_weight','image_2','image_3');
        $earrings = &$jewelleryEarringsData;
        $carat = array();
        $amount = array();
        $metal = array();
        if(isset($data['metal'])){
            $metal = $data['metal'];
            //$earrings->whereIn('metal_type', $metal);
            foreach($metal as $valk){
                $earrings->orWhere('metal_type', 'like', '%'.$valk.'%');
            }
        }
        if(isset($data['amount']['1']) && $data['amount']['1'] !=''){
            $amount = $data['amount'];
            $amt1 = $amount['0'];
            $amt2 = $amount['1'];
            $earrings->whereBetween('price',[$amt1,$amt2]);
        }
        if(isset($data['carat']['1']) && $data['carat']['1'] !=''){
            $carat = $data['carat'];
            $carat1 = $carat['0'];
            $carat2 = $carat['1'];
            $earrings->where('total_weight','>=',$carat1)->where('total_weight','<=',$carat2);
        } 
        $jewelleryEarringsData = $earrings->where('item_type', $filter)->get();
    }
}

So the code where I'm using orWhere function of Laravel is giving me abnormal results.

Upvotes: 1

Views: 62

Answers (2)

Rohit shah
Rohit shah

Reputation: 819

Please Change your

$jewelleryEarringsData = Jwellery::select('id','name','price','msrp','metal_type','image_url','total_weight','image_2','image_3');

To

$jewelleryEarringsData = Jwellery::select('id','name','price','msrp','metal_type','image_url','total_weight','image_2','image_3')->get();

And also re-assign values back to earring variables. Hope this helps you

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

Change your code to this:

foreach ($metal as $valk){
    $earrings = $earrings->orWhere('metal_type', 'like', '%'.$valk.'%');
}

Upvotes: 0

Related Questions