Level 14
Can you please describe what is the problem and what is your expected result;
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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();
});
}
Please or to participate in this conversation.