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

newnewcat's avatar

How to use Laravel API Resource to create Javascript associative array in JSON

Hi. The question is simple. Say I have a model "Product" with "id", "product_name" and "price" attributes. It would be nice to use Laravel API Resource to generate Javascript associative array in JSON e.g.

{"1":{"name": "Hello World Book","price":100},"2":{"name":"Fairy Tale Book","price":0}}

With "1" and "2" being the ID. It is nice as I can then use it to get each product quickly by "id" in Javascript.

The question is I have no idea it it can be done and if it is possible at all. I tried various ways with no luck.

Thanks for your ideas in advance!

0 likes
3 replies
CarbonNanotubes's avatar

You will need a Resource and a Resource Collection. Your resource would look something like this.


<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'    => $this->id,
            'name'  => $this->name,
            'price' => $this->price
        ];
    }
}

Which would return json like this

{
    "id": 1,
    "name":  "Hello World Book",
    "price": 100
}

and your resource collection would look something like this

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class ProductsResource extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => ProductResource::collection($this->collection)
        ];
    }
}

this would return something like this

"data": [
    {
    "id": 1,
    "name":  "Hello World Book",
    "price": 100
    },
    {
    "id": 2,
    "name":  "Fairy Tale Book",
    "price": 0
    }
]
CarbonNanotubes's avatar

in your controller you would using it like this

public function index()
    {
        return new ProductsResource(Product::all());
    }

    public function show(Product $product) {

        ProductResource::withoutWrapping();

        return new ProductResource($product);
    }
newnewcat's avatar

Thanks shaqaruden. But the goal is not:

[{"id": 1, "name": "Hello World Book", "price": 100}, {"id": 2, "name": "Fairy Tale Book", "price": 0}

It should be:

{"1":{"name": "Hello World Book","price":100},"2":{"name":"Fairy Tale Book","price":0}}

I can achieve this by doing:

Product::all()->keyBy('id')->toJson()

I wonder if Laravel API Resource can do the same thing or not.

Please or to participate in this conversation.