Posts Learn Components Snippets Categories Tags 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

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

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

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

View Components

Other Code Snippets

More