Home > Back-end >  Laravel combine resource collection when returning response
Laravel combine resource collection when returning response

Time:12-19

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?

CodePudding user response:

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.

  • Related