Have you looked at some nested set packages for laravel.
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');
}
}
@ComputerMaverick one is https://github.com/lazychaser/laravel-nestedset
But do a Youtube search for laravel nested set, there are some that may give you some ideas on which way to proceed.
Please or to participate in this conversation.