laravel collection sort review

1 year ago 27
Nature

To sort a Laravel collection of product details by positive, negative, ingredients, or materials, you can use the sortBy method of the Illuminate\Support\Collection class. Heres an example of how to sort a collection of products by their name in ascending order:

$products = collect([
    [name => Product C, type => negative],
    [name => Product A, type => ingredients],
    [name => Product B, type => positive],
    [name => Product D, type => materials],
]);

$sortedProducts = $products->sortBy(name);

$sortedProducts->all();

This will output:

[
    [name => Product A, type => ingredients],
    [name => Product B, type => positive],
    [name => Product C, type => negative],
    [name => Product D, type => materials],
]

To sort the collection by type, you can simply replace name with type in the sortBy method:

$sortedProducts = $products->sortBy(type);

$sortedProducts->all();

This will output:

[
    [name => Product A, type => ingredients],
    [name => Product D, type => materials],
    [name => Product C, type => negative],
    [name => Product B, type => positive],
]

Note that the sortBy method sorts the collection in ascending order by default. If you want to sort the collection in descending order, you can use the sortByDesc method instead.