Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ranslobo's avatar

Orderby date wont show in order when echo to screen

When I query the database I get a collection ordered by date exactly how I need it. But when I run foreach loop and echo the screen its all messed up the order.

Why this is happening...?

Schema::create('units', function (Blueprint $table) {
            $table->increments('id');
            $table->string('number')->unique();
            $table->integer('publish')->default(0);
            $table->date('available_on')->nullable();
});
$units = DB::table('units')->orderBy('available_on', 'asc')->where('publish', 1)->get();
foreach ($units as $unit) {
        if ($unit->available_on <= Carbon::now()) {
            echo "{$unit->number} Available Now" . '<br>';
        } else {
            $date = date_create($unit->available_on);
            echo $unit->number . ' ' . date_format($date, "M d - Y") . '<br>';
        }
    }
0 likes
4 replies
rin4ik's avatar
$units = DB::table('units')->where('publish', 1)->orderBy('available_on', 'asc')->get(); 
1 like
rin4ik's avatar

@ranslobo problem is with your if statements.

$units = DB::table('units')->orderBy('available_on', 'asc')->where('publish', 1)->get();
dd($units);

you will get ordered list

ranslobo's avatar
ranslobo
OP
Best Answer
Level 32

yes I know, like I said... I do get a collection exactly how I want it but when I echo to the screen its all messed up.

But I just tried it on the crappy Internet explorer (edge) and it actually work fine lol..

Not sure why it show all messed up in Chrome.

Thanks anyway!!

Please or to participate in this conversation.