Search code examples
phplaravellaravel-collection

Sorting on a translable json column


I am using spatie translation package in laravel. I have collection which i want to sort by name but the name column has a json collection due to which its not getting sorted. I have tried

$shoptype->categories->sortBy('name.en');

and my result

{
"id": 8,
"type_id": 1,
"name": "{\"en\":\"Other Meats\",\"es\":\"Otras Carnes\"}",
"image_path": "http://market.test/uploads/category/Cpaf7nCVZxshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-08-14T06:17:35.000000Z",
"deleted_at": null
},
{
"id": 9,
"type_id": 1,
"name": "{\"en\":\"Turkey\",\"es\":\"Pavo\"}",
"image_path": "http://market.test/uploads/category/8U2qP2mrzashoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:01.000000Z",
"deleted_at": null
},
{
"id": 10,
"type_id": 1,
"name": "{\"en\":\"Chicken\",\"es\":\"Pollo\"}",
"image_path": "http://market.test/uploads/category/SnP7mwnTeBshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:14.000000Z",
"deleted_at": null
},
{
"id": 11,
"type_id": 1,
"name": "{\"en\":\"Beef\",\"es\":\"Carne De Vaca\"}",
"image_path": "http://market.test/uploads/category/b7IKzAGUHDshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:50.000000Z",
"deleted_at": null
}```





Solution

  • Use SortBy with callback.

    use collect method to convert categories as collection if not

    $categories = collect($shoptype->categories)->sortBy(function($category, $key){
           return (json_decode( $category->name))->en;
    });
    

    if $shoptype->categories is already a collection

    $categories = $shoptype->categories->sortBy(function($category, $key){
           return (json_decode( $category->name))->en;
    });
    

    if categories is Json then use json_decode($shoptype->categories); and use sortBy with collect method

    https://laravel.com/docs/8.x/collections#method-sortby