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

freemium's avatar

multi level category API Resource

is this api resource is correct controller

    public function index()
    {
        $categories = Category::where('parent_id', null)->with('children')->get();
        return CategoryResource::collection($categories);
    }

CategoryResource is here


class CategoryResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'created_at' => (string) $this->created_at,
            'children_count' => $this->children()->count(),
            'children' => ChildrenResource::collection($this->whenLoaded('children')),

        ];
    }
}

childrenResource

class ChildrenResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'created_at' => (string) $this->created_at,
            'children_count' =>
            $this->children(),
            'children' => ChildrenResource::collection($this->whenLoaded('children')),
        ];
    }
}

category model

   public function children()
    {
        return $this->hasMany(Category::class, 'parent_id')->with('children');
    }

//respective migration
{
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name', 50)->unique();
            $table->string('slug')->nullable();
            $table->foreignId('parent_id')->nullable()->constrained('categories')->cascadeOnDelete();
            $table->boolean('is_featured')->default(false);
            $table->timestamps();
        });
    }
0 likes
1 reply
manojo123's avatar

Can you please describe what is the problem and what is your expected result;

Please or to participate in this conversation.