laravellaravel-collection

Sort By with function on collection laravel


I would like some help on this, i have a table like this

CREATE TABLE IF NOT EXISTS `items` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
   `code` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
    `unitPrice` decimal(8,2) NOT NULL,
  `quantity` int(11) NOT NULL,
  `totalSold` int(11) DEFAULT NULL,
   `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

and after using DB::table('items')->get(); i would like to get the same result as if i run this sql command

"select `code`,(`unitPrice`*(`quantity`+`totalSold`)) as totalEarnIfsold from `items` order by `totalEarnIfsold` desc"

what i have been able to achieve without success ofc is this:

    $items_all->sortBy([
          $totalEarnIfsold=  fn ($a) => $a->unitPrice *($a->quantity+$a->totalSold),
          ['totalEarnIfsold', 'desc'],           
        ]);

So i need your help if you may ofc, and thanks


Solution

  • You can do in following way

    First you need to calculate totalEarnIfsold with map function and after that you can easily sort with value.

    $items_all = $items_all->map(function($item) {
            $item->totalEarnIfsold = $item->unitPrice *($item->quantity + $item->totalSold);
            return $item;
            })->sortByDesc('totalEarnIfsold');