Ad

Laravel Chains Of Wheres

- 1 answer

I am working with laravel and making a query with filters, i am not sure how to do that but i have an idea, this is what i want.

            $wheresMethodsChain;

            $type = "house";
            $model = "paper";
            // sometimes it could be empty
            $size = "";

            if ($type != "") {
                // add to chain to call later
                add_to_my_chain_of_wheres( $wheresMethodsChain , ->where('type',$type) );
                // wheresMethodsChain = ->where('type',$type)
            }
            if ($model != "") {
                add_to_my_chain_of_wheres( $wheresMethodsChain , ->where('model',$model) );
                // wheresMethodsChain = ->where('type',$type)->where('model',$model)

            }
            if ($size != "") {
                add_to_my_chain_of_wheres( $wheresMethodsChain , ->where('size',$size) );
                // wheresMethodsChain =  ->where('type',$type)->where('model',$model)

            }
            // the final chain should be something like this, only two because the "$size" variable is empty
            // ->where('type',$type)->where('model',$model)

            // Finally add the chain of wheres at the end of my query
            $regs = DB::table('mytable')->paginate(10)->wheresMethodsChain;

thanks for any help

Ad

Answer

This is how you would do that:

$query = DB::table('mytable');

if($type){
    $query = $query->where('type', $type);
}
if($model){
    $query = $query->where('model', $model);
}
if($size){
    $query = $query->where('size', $size);
}

$results = $query->paginate(10);
Ad
source: stackoverflow.com
Ad