Friday, March 31, 2017

Fetch Data based on micro-level filters - Laravel

Here is the scenario,

I want to fetch Shipper ChargeHeads based on Customer ID, His Branch and His product but if the charges are null then I just want to consider his ID and the Branch if still the charges are null then I just want to consider his ID and even though the charges are null I just want to take the default charges with Customer ID=0, Branch ID = null and Product Description = null Below is my code which is working perfectly, but is there a way to optimize it.

In charges table I have Customer ID, Branch ID, Product Description,Is Active charges,

$charges = null;
    //Getting Shipper ChargeHeads corresponding to his branch and product Description
    $charges = \App\ShipperChargeHead::where('customer_id', $customer_id)
                                      ->where('branch_id', $branch_id)
                                      ->where('product_description', $product_description)
                                      ->where('is_active', 1)
                                      ->select('customer_id','active_charges_data','inactive_charges_data')
                                      ->first();
    if ($charges == null) {
        //Getting Shipper ChargeHeads corresponding to his branch.
        $charges = \App\ShipperChargeHead::where('customer_id', $customer_id)
                                          ->where('branch_id', $branch_id)
                                          ->where('is_active', 1)
                                          ->select('customer_id','active_charges_data','inactive_charges_data')
                                          ->first();
    }
    if ($charges == null) {
        //Getting Shipper ChargeHeads
        $charges = \App\ShipperChargeHead::where('customer_id', $customer_id)
                                          ->where('is_active', 1)
                                          ->select('customer_id','active_charges_data','inactive_charges_data')
                                          ->first();
    }
    if ($charges == null) {
        //Getting Default
        $charges = \App\ShipperChargeHead::where('customer_id', '0')
                                          ->where('branch_id', null)
                                          ->where('product_description', null)
                                          ->where('is_active', 1)
                                          ->select('customer_id','active_charges_data','inactive_charges_data')
                                          ->first();
    }
    return $charges;



via Akshay Khale

Advertisement