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

ComputerMaverick's avatar

Query Categories with Nth Child Category

I have a the below category model. How do i perform a query that first returns the parent category and the can subsequently query for its child category irrespective of the depth.

With my existing model i can query a child category using the childrenCategories on blade. I would like to return this information via an api get. That is to say something like this:

How i think the controller should look

<?php

namespace blablabla;

use blablabla;

class blablabla {
public function getNthSub(){
		$nthsub = Category::select([
					 'title',
      				  'subtitle',
       				 'category_id',
       				 'img',
       				 'video',
        				'status',
						])->whereNull('category_id')->where('id', '!=', 1)->get()
		}
}

Actual Categories Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'title',
        'subtitle',
        'category_id',
        'img',
        'video',
        'status',
    ];

    public function parent()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function childrenCategories()
    {
        return $this->hasMany(Category::class, 'category_id');
    }
}
0 likes
3 replies
jlrdw's avatar

Have you looked at some nested set packages for laravel.

1 like

Please or to participate in this conversation.