Tuesday, May 8, 2018

use external functions to calculate value in eloquent queries - development

use external functions to calculate value in eloquent queries

I have created a filter for products in laravel 5.5

I want to filter the price range (min:max) but the price column in db is not the price that i am using to show on product page.

I have 2 more columns TVA, Profit and an external function that calculate the price for sale.

The calcPrice function take those arguments (price, tva, profit)

calcPrice($price, $tva = 0, $profit = 0)

In the controller for filters logic i use this approach:

// Product model
$products = Product::query();
// use for appends with pagination
$queries = [];
// all the conditions for the query
$filterCondition = array(
        ['IsActive', '1'],
        ['CategoryID', $currentCategory->CategoryID]
    );
// brand filter
if(request()->has('brand')){
   $filterBrands = explode(":", request('brand'));
   $products = $products->whereIn('BrandID', $filterBrands);
   $queries['brand'] = request('brand');
}
...
if(request()->has('price')){
   $filterPrice = explode(":", request('price'));
   $min = $filterPrice[0];
   $max = $filterPrice[1]; 
   $products = $products->whereBetween('Price', [$min, $max]);
   $queries['price'] = request('price');           
}

// the final query
$products = $products->where($filterCondition)->paginate(9)->appends($queries);

Is there a way to calculate the final price in select in eloquent?

ex: calcPrice(Price, TVA, Profit) as finalPrice then use the finalPrice field to compare between



from Laravel Questions and Answers https://laravelquestions.com/php/use-external-functions-to-calculate-value-in-eloquent-queries/
via Lzo Media

No comments:

Post a Comment