0

I have a resource which looks like so;

class TestingResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'first' => AnotherResource::collection($this->first),
            'second' => AnotherResource::collection($this->second),
        ];
    }
}

What I want to do is combine the 2 so I only have to return one element like so;

class TestingResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'first' => AnotherResource::collection($this->combined),
        ];
    }
}

I tried doing array_merge($this->first, $this->second) but it doesnt work.

Is there any way of getting this to work?

CodeSauce
  • 255
  • 3
  • 19
  • 39
  • This will help - https://stackoverflow.com/questions/30522528/how-to-merge-two-eloquent-collections – T.Shah Dec 16 '22 at 07:04

1 Answers1

2

You can use the concat() for collections like:

public function toArray($request)
{
    $first = FirstResource::collection(First::all());
    $second = SecondResource::collection(Second::all());

    $combined = new Collection();
    return $combined->concat($first)->concat($second);
}

This concatenates key. The merge() will overwrite the values.

francisco
  • 1,387
  • 2
  • 12
  • 23