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".
Leave a reply