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?

6
  • 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. Commented Mar 28, 2021 at 8: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. Commented Mar 28, 2021 at 8: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. Commented Mar 28, 2021 at 8:22
  • Can you give me an example? Commented Mar 28, 2021 at 8:24
  • Maybe try: laravel.com/docs/8.x/eloquent-resources#data-wrapping Commented Mar 28, 2021 at 8:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.