Order by a collection based on two columns

151
March 02, 2018, at 10:52 PM

Given I have a simple collection

$collection = collect([
    ['product' => 'Desk', 'price' => 200, 'cost'=>250],
    ['product' => 'Chair', 'price' => 100, 'cost'=>200],
]); 

I calculate the income in vuejs by simply doing price - income, in this case I will get:

  1. -50
  2. -100

Now I want to order by descending the results like:

  1. -100
  2. -50

Wonder if there is a way to order by in the collection itself ?

Answer 1

You could do this in Laravel and pass the data to the view if it's an option. Use the sortBy() and sortByDesc() methods:

$asc = $collection->sortBy(function ($i) {
    return $i['price'] - $i['cost'];
});
$desc = $collection->sortByDesc(function ($i) {
    return $i['price'] - $i['cost'];
});

Alternatively, you can add a new column to the collection using the transform() method, so you'll be able to sort it with any JS script:

$collection->transform(function ($i) {
    $i['difference'] = $i['price'] - $i['cost'];
    return $i;
});
READ ALSO
Convert an excel to pdf using phpSpreadsheet

Convert an excel to pdf using phpSpreadsheet

I'm using phpSpreadsheett to convert an Excel file already in memory to a pdf, but I'm obtaining this fatal error message

997
Creating PDF from Database Content [on hold]

Creating PDF from Database Content [on hold]

I am searching for the "best practice" when it comes to rendering big PDFs (10-100 pages) from database contentI have googled a bit and found fpdf which looks okay to me but I was wondering if there is better software for this job (PHP or JS)

119
TCPDF image color is not working properly (giving black and white color)

TCPDF image color is not working properly (giving black and white color)

I am using TCPDF Library to generate dynamic PDFI have put an image logo in the document but the image is showing black and white instead of original colors

252
Change image in PDF

Change image in PDF

Hi I keep getting this error: Runtime Deprecated code usage - Imagick::clone method is deprecated and it's use should be avoided

181