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

waleedviews's avatar

Laravel Nova Self-referential hasMany relationship

I have a table which has categories and child categories and it has relation with the same table.

this is my model relationship, i use Scope to get all the parent categories,

public function ScopeRoot($query)
    {
        $query->whereNull('parent_id');
    }

    public function childSpeciality()
    {
        return $this->hasMany(Speciality::class, 'parent_id');
    }

This is my nova Resource

public function fields(NovaRequest $request)
    {
        return [
            //ID::make(),
            hasMany::make('Child Speciality', 'childSpeciality', Speciality::class),
            Text::make('Category', 'name'),
        ];
    }

it only display a parent categories and not child categories, any help please?

thank you.

0 likes
1 reply
azimidev's avatar

Are you only displaying the parent categories in your Nova resource and not the child categories?

what about this:

public function fields(NovaRequest $request)
{
    return [
        //ID::make(),
        hasMany::make('Child Speciality', 'childSpeciality', Speciality::class)->withMeta(['value' => function () {
            return $this->childSpeciality->map(function ($speciality) {
                return $speciality->name;
            })->implode(', ');
        }]),
        Text::make('Category', 'name'),
    ];
}

loops over the child categories, retrieve their names and then concatenate them into a comma-separated string. The resulting string will be displayed in the Child Speciality field of your Nova resource

Please or to participate in this conversation.