Ad

Use Of Include In Fractal Transformer Laravel 5?

- 1 answer

I used this library for adding fractal transformer to my json output.

//This is main tranformer for service provider enquiry transformer

  class CustomerVehicleTransformer extends TransformerAbstract {

          protected $defaultIncludes = [
            'service_provider_enquries'
        ];
        public function transform(CustomerVehicle $customerVehicle) {
           
                return [
                     'id'      => (int) $customerVehicle->id,
                    'status'   =>$customerVehicle->vehiclenumber
                    ];
            }

       public function includeServiceProviderEnquries(CustomerVehicle $customerVehicle) {

            $serviceProvider = $customerVehicle->service_provider_enquries;
            return $this->item($serviceProvider, new ServiceProvidersEnquiryTransformer);
        }
    }

class ServiceProvidersEnquiryTransformer extends TransformerAbstract {


    public function transform(ServiceProvidersEnquiry $book) {
        return [
            'modeofpayment'      => (int) $book->modeofpayment
        ];
    }


}
calling from controller

       $manager =new Fractal\Manager();
        if (isset($_GET['include'])) {
            $manager->parseIncludes($_GET['include']);
        }
        $json = $manager->createData($resource)->toJson();
         echo $json;

When I try to run this code it throws the following error:

Argument 1 passed to App\Acme\FractalTransformers\ServiceProvidersEnquiryTransformer::transform() must be an instance of App\ServiceProvidersEnquiry, null given, called in /home/aidor/Documents/ozoServer/vendor/league/fractal/src/Scope.php on line 307 and defined

What could be the problem? Suggest, please, some example of defaultincludes and availableIncludes.

Ad

Answer

The error is saying that $resource is null, you need to pass it an instance of ServiceProvidersEnquiry you're also missing some key lines of code to set up the response. Double check the documentation to check you're doing everything right and understand WHY it's not working: http://fractal.thephpleague.com/transformers/

You should be doing something like this I think:

// set up data
$enquiry = App\ServiceProvidersEnquiry::first();

// set up fractal manager
$manager = new Fractal\Manager();

if (isset($_GET['include'])) {
    $manager->parseIncludes($_GET['include']);
}

$fractal->setSerializer(new Fractal\Serializer\ArraySerializer());

// set up response item
$response = new Fractal\Resource\Item($enquiry, new \PathToYourTransformer\ServiceProvidersEnquiryTransformer);

return response()->json($fractal->createData($response)->toArray());
Ad
source: stackoverflow.com
Ad