On Octobercms frontend results does't respect array order

131 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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

0
On

Depends on how you are ordering. Use the Laravel collections to order the array. Twig will print ascending priortizing numeral indexes. [5,4,2,3,1] will always come out as [1,2,3,4,5]. So a Laravel collection that has [0, 1, 2] you can use the ->sortBy method to switch up which model instance attacked to the index.

So you might have a model that contains a name field. Your first record's name is John and your last is Adam. Twig will display John to Adam. Using the ->sortBy('name') will display alphabetically ascending list.

[0=>['name'=>'John'], 1=>['name'=>'Zack'], 2=>['name'=>'Adam']] 
//Using ->sortBy('name') becomes:
[0=>['name'=>'Adam'], 1=>['name'=>'John'], 2=>['name'=>'Zack']]