Get Best Selling Products Efficient Query in Laravel
Categories - Laravel PHP Framework Tags - PHP Laravel   Maniruzzaman Akash   2 years ago   4035   1 minute   29

Get Best Selling Products Efficient Query in Laravel

Get Best selling products for your Ecommerce Store in Laravel - 

So, assume we've a transaction_sell_lines table which is connected to TransactionSellLine eloquent model.

Item table - items

Transaction Sell Items table - transaction_sell_lines

 

Laravel Code snippet - 

public function getBestSellingProducts($limit = 10)
{
   $bestSellingProducts = TransactionSellLine::select(
            'item_id',
            'items.name as item_name',
            'items.sku as item_sku',
            DB::raw('SUM((quantity * unit_price_inc_tax) - discount_amount - item_tax) as total_sale')
   )
   ->leftJoin('items', 'items.id', '=', 'transaction_sell_lines.item_id')
   ->groupBy('item_id')
   ->orderBy('total_sale', 'desc')
   ->limit($limit)
   ->get();

   return $bestSellingProducts;
}

 

We've actually used the DB::raw query inside select.

DB::raw('SUM((quantity * unit_price_inc_tax) - discount_amount - item_tax) as total_sale')

Then, use descending order - 

->orderBy('total_sale', 'desc')

 

Very simple to implement best selling products in laravel, right ?

Previous
PHP If-else-elseif and Switch-case
Next
PHP String Functions - All necessary String functions in PHP to manage strings better.