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?
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
thenFIELD sort is not available
. alternatively if you havesmall amount of records
you can sort itclient 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
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page