Sabonzy
1596
3
Laravel

API Resource and passing data to blade view

Posted 1 year ago by Sabonzy

i am using the api resource to to transform the models before returning it a vue component through blade view but the data returned is not the transformed model but the raw model itself. Interestingly when the data is returned directly without passing it to the view then it will be formatted as described in the toArray method.

here is the controller:

 class PreApprovedController extends Controller
    {
        private $applicants;

        public function __construct(PersonalDetailsRepository $applicants)
        {
            $this->applicants = $applicants;
        }

        
        public function show($id)
        {

            $applicant = $this->applicants->withCriteria(
                    new WithRelations(
                        [
                            'batteries',
                            'inverters',
                            'solarPanels',
                            'bosInfo',
                            'location',
                        ]
                    ))->find($id);
          //  dd(new InspectionsResource($applicant)); this returns the raw model model not the transformed one
            // return new InspectionsResource($applicant); this returns the the transformed model

        $applicant = new InspectionsResource($applicant));

            return view('approved.inspections.create', compact('applicant'));
        }
    }

the api resource:

class InspectionsResource extends JsonResource
    {

        public function toArray($request)
        {
            return [
                "id"                    => $this->id,
                "full_name"             => $this->full_name,
                "phone_number"          => $this->phone_number,
                "identification_type"   => $this->identification_type,
                "identification_number" => $this->identification_number,
                "postal_address"        => $this->postal_address,
                "email"                 => $this->email,
                "profession"            => $this->profession,
                "company_name"          => $this->company_name,
                "company_location"      => $this->company_location,
                "location"              => new LocationsResource($this->whenLoaded('location')),
                "batteries"             => new BatteriesResource($this->whenLoaded('batteries')),
                "inverters"             => new InvertersResource($this->whenLoaded('inverters')),
                "solar_panels"          => new SolarPanelsResource($this->whenLoaded('solarPanels')),
                "bos_info"              => new BoSResource($this->whenLoaded('bosInfo')),
            ];
        }
    }

formatted data is also return when i convert it collections. how do i get the transformed data returned when getting a single model

Please sign in or create an account to participate in this conversation.