laravel sort by value code example

Example 1: sort laravel eloquent

$posts = Post::orderBy('id', 'DESC')->get();

Example 2: laravel sort collection by key

$collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy('price');

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'price' => 100],
        ['name' => 'Bookcase', 'price' => 150],
        ['name' => 'Desk', 'price' => 200],
    ]
*/

Example 3: get all sort by laravel

$results = Project::orderBy('name')->get();

Tags:

Php Example