Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

panthro's avatar

API Resource for non APIs

I'm aware when building an API, you can use API Resources to modify data from the database, to present it to thE front end.

But, with a standard/Inertia application, I return data from the model, but I find that I would like a middle layer to transform the data before it's passed back to JS and rendered.

What can I utilize to do this?

0 likes
8 replies
jlrdw's avatar

You can just loop over a returned eloquent result. You shouldn't need to transform anything.

panthro's avatar

@jlrdw I want to transform a couple of fields into an array so this can be looped out in JS.

panthro's avatar

@jlrdw yes but for consistency and caching it’s best to do it on the back end

wojakmcwagies's avatar

Do you mean something like this:

return inertia('ProductsAndSolutions/Published', [
                'productsAndSolutions' => ProductAndSolution::where('published_at', '!=', null)
                    ->orderByDesc('id')
                    ->get()
                    ->map(fn ($productAndSolution) => [
                        'id' => $productAndSolution->id,
                        'image' => $productAndSolution->image,
                        'image_size' => $productAndSolution->image_size,
                        'starred' => $productAndSolution->starred,
                        'system' => $productAndSolution->system,
                        'description' => $productAndSolution->description,
                        'featured' => $productAndSolution->featured,
                        'updated_at' => $productAndSolution->updated_at,
                        'published_at' => $productAndSolution->published_at,
                    ]),
                'countAll' => $countAll,
                'countPublished' => $countPublished,
                'countDrafts' => $countDrafts,
                'countTrash' => $countTrash,
            ]);

You can do anything with the data here.

wojakmcwagies's avatar

@panthro Like this?

    public function __construct($status, $message, $resource)
    {
        parent::__construct($resource);
        $this->status  = $status;
        $this->message = $message;
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'success'   => $this->status,
            'message'   => $this->message,
            'data'      => $this->resource
        ];
    }
1 like

Please or to participate in this conversation.