Posts Learn Components Snippets Categories Tags Tools new About
/

Sort Model by Day (Monday to Sunday) in Laravel

Learn how to sort model by day using the sortBy() method to get value from "Monday" to "Sunday"

Created on Aug 01, 2021

68 views

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".

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

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)