Home / Snippets / Sort Model by Day (Monday to Sunday) in Laravel
Sort Model by Day (Monday to Sunday) in Laravel cover

Sort Model by Day (Monday to Sunday) in Laravel

1.2K

3 years ago

0 comments

To sort model by day (Monday to Sunday) you can make use of the "sortBy()" method which returns the day constant from 0 to 6 by using the Carbon\Carbon constant day value.

Assuming that you want to sort the "Article" model like below, you can perform the query as follows.
<?php

use App\Models\Article;

$data = Article::query()
    ->groupBy('day')
    ->get()
    ->sortBy(function ($article) {
        # assuming $article->day return "Monday", "Tuesday" and etc
        return constant('\Carbon\Carbon::' . strtoupper($article->day));
    })
    ->toBase();

Using the arrow function can be like below.
<?php

use App\Models\Article;

$data = Article::query()
    ->groupBy('day')
    ->get()
    ->sortBy(function ($article) => constant('\Carbon\Carbon::' . strtoupper($article->day)))
    ->toBase();

Do not that the code above will return the value in a Sunday to Saturday order. If you want them ordered Monday to Sunday, you're going to need to tweak it a little.
<?php

use App\Models\Article;

$data = Article::query()
    ->groupBy('day')
    ->get()
    ->sortBy(function ($article) => (6 + constant('\Carbon\Carbon::'.strtoupper($job->day))) % 7)
    ->toBase();

Now you will get the order from "Monday" to "Sunday".
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this