Laravel/ PHP: Order By Alphabetical with numbers in order [duplicate]



PHP Snippet 1:

DB::table('test')->orderBy('LENGTH(title)', 'ASC')
    ->orderBy('title', 'ASC')
    ->get();

PHP Snippet 2:

SELECT * FROM <table> ORDER BY CAST(<column> AS unsigned)

PHP Snippet 3:

DB::table('test')
    ->orderByRaw("CAST(title as UNSIGNED) ASC")
    ->get();

PHP Snippet 4:

$collection = $collection->sortBy('order', SORT_REGULAR, true);

PHP Snippet 5:

DB::table('test')->orderByRaw('LENGTH(title)', 'ASC')
->orderBy('title', 'ASC')
->get();

PHP Snippet 6:

$collection = collect([
    ['sn' => '2'],
    ['sn' => 'B'],
    ['sn' => '1'],
    ['sn' => '10'],
    ['sn' => 'A'],
    ['sn' => '13'],
]);

PHP Snippet 7:

//print_r($collection);

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [2] => Array
                (
                    [sn] => 1
                )

            [0] => Array
                (
                    [sn] => 2
                )

            [3] => Array
                (
                    [sn] => 10
                )

            [5] => Array
                (
                    [sn] => 13
                )

            [4] => Array
                (
                    [sn] => A
                )

            [1] => Array
                (
                    [sn] => B
                )

        )

)

PHP Snippet 8:

//print_r($sorted)

Array
(
    [0] => Array
        (
            [sn] => 1
        )

    [1] => Array
        (
            [sn] => 2
        )

    [2] => Array
        (
            [sn] => 10
        )

    [3] => Array
        (
            [sn] => 13
        )

    [4] => Array
        (
            [sn] => A
        )

    [5] => Array
        (
            [sn] => B
        )

)

PHP Snippet 9:

$sorted = $collection->sortBy(function ($item, $key) {
    //your logic
});

PHP Snippet 10:

$unorderedThings = Thing::orderBy('id')->get();
$orderedThings=$unorderedThings->sort();

PHP Snippet 11:

$tests = Test::all();
$tests = $tests->sortBy('title', SORT_REGULAR, false); // false=ascending, true=descending