octobercmsoctobercms-backendoctober-form-controlleroctober-partial

On Octobercms frontend results does't respect array order


I'm using a yaml file with a repeater field to select some categories on backend.

Then on partial i use:

$categories = \...\..\Category::whereIn('id', $categories)->get();
$this['categories'] = $categories;

Then on fronted i use:

{% for category in categories%}
    {{ category.name }}
{% endfor %}

Everything is working fine and i get all categories of array variable $categories in frontend. The problem is than no matter if i change the array order the result order is always the same. For example this array:

$categories = [1, 2, 3, 4, 5];

gives the same order results with this array:

$categories = [4, 1, 2, 5, 3];

Is there a way to make it respect array order?


Solution

  • if you are using mysql its easy to customise order based on what order you are passing your id.

    $categories = [4,5,1,3];
    $sortedCategories = \...\..\Category::whereIn('id', $categories)
        ->orderByRaw(\DB::raw("FIELD(id," . implode(',', $categories) .  ")"))
        ->get();
    

    it will created sort on FIELD(id, 4,5,1,3) assuming $categories = [4,5,1,3] and your records will be sorted like that.

    Client side

    Or if you are using SQlite then FIELD sort is not available. alternatively if you have small amount of records you can sort it client side using collection helper method sortBy.

    $category = [1,2,4,5,3];
    $categories = \...\..\Category::whereIn('id', $categories)->get();
    $sortedCategories = $categories
        ->sortBy(function ($item) use ($category) {
            return array_search($item->id, $category);
        });
    dd($sortedCategories); // sorted based on $category = [1,2,4,5,3]
    

    if any doubts please comment