0
<?php

namespace App\Http\Resources;

    use Illuminate\Http\Resources\Json\ResourceCollection;
    
    class LanguageCollection extends ResourceCollection
    {
        public $collects = LanguageResource::class;
    
        /**
         * TagCollection constructor.
         * @param $resource
         */
        public function __construct($resource)
        {
            parent::__construct($resource);
        }
    
        /**
         * Transform the resource collection into an array.
         *
         * @param \Illuminate\Http\Request $request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'languages' => parent::toArray($request)
            ];
        }
    }

This would give a response structure as follows:

enter image description here

But I want to put all the languages with in another wrapper called "result" so the response structure will look like this:

enter image description here

I don't want to hard code it this way cause this would require us to change every resource collecction.

   public function toArray($request)
    {
        return [
            'result' => ['languages' => parent::toArray($request)]
        ];
    }

What is the correct way to achieve this response structure?

Ask17
  • 72
  • 8
  • You will have to edit it manually, but why would you like to add `result` to every response ? I think that you can also play with Middlewares, so when you have a response for the desired route that should have that `result`, I think you can add it there. – matiaslauriti Mar 28 '21 at 08:08
  • This can be done with Overriding the Resource Collection but I don't know how to do that. and I don't want to do it manually. – Ask17 Mar 28 '21 at 08:09
  • 1
    @Ask17 what you do not know about extending the ResourceCollection? You just need to extend the ResourceCollection and override the method and then pass an instance to it instead of the previous one. – Sachin Bahukhandi Mar 28 '21 at 08:22
  • Can you give me an example? – Ask17 Mar 28 '21 at 08:24
  • Maybe try: https://laravel.com/docs/8.x/eloquent-resources#data-wrapping – Sachin Bahukhandi Mar 28 '21 at 08:31
  • That I know, I want to add another field wrapper called 'result' within that 'data' wrapper. – Ask17 Mar 28 '21 at 08:39

0 Answers0