1

I am newbie in Laravel. I am using laravel as a REST End Point, I use Eloquent: API Resources for transforming my data to JSON.

I am using Collection and Resource to parse my data came from my query. So below is the structure of my response:

data:
    0
        id
        name
    1
        id
        name

Now I need to have some categorization in the data, hence I require the data structure to be in below format

data:
    24H
        0
            id
            name
        1
            id
            name
    7D
        0
            id
            name
        1
            id
            name

I tried couple of ways to accomplish this, the static way I tried for testing was to change the ResourceCollection's toArray method and append the key 24H for the data we get.

But I know that is not correct and generic way.

I would like to know how I can achieve the above response format in generic and extensible manner.

Your help is much appreciated.

Thanks.

Sharad Soni
  • 378
  • 1
  • 5
  • 18
  • Are the 24H and 7D keys coming from some property of the models? – Alec Joy Jan 31 '20 at 19:14
  • I have executed my own select query to get the data. I can add another column as type that is 24H or 7D in the SQL itself, if that can be used anywhere. – Sharad Soni Jan 31 '20 at 19:16

1 Answers1

1

Laravel Collections have a groupBy method that may help you here, make sure the column you want to use as the key is selected as well. So if you have

data: 
    0: 
        id: 1
        name: Bob
        category: 24H

    1: 
        id: 2
        name: Bill
        category: 7D

Then $data->groupBy('category') would return the following

data: 
    24H:
        0: 
            id: 1
            name: Bob
            category: 24H

    7D: 
        0:
            id: 2
            name: Bill
            category: 7D
Alec Joy
  • 1,848
  • 8
  • 17
  • Thanks, however I have a huge query so I use DB::select and provided my RAW query in it. I tried using groupBy in it, but it gave error ```Call to a member function groupBy() on array``` This is my syntax: ```DB::select($sql, [$this->user['id']])->groupBy('type');``` – Sharad Soni Jan 31 '20 at 19:40
  • Take the array you get back from the DB::select and put it in a collection first collect(DB::select($sql, [$this->user['id']))->groupBy('type') – Alec Joy Jan 31 '20 at 19:44
  • Thanks for your answer, it worked after some modification on resource class where I transform data into array. – Sharad Soni Jan 31 '20 at 20:41