Skip to content
Advertisement

Laravel Nova Self-referential Relationship

In Laravel, if I want to create a self-referential relationship I can do the following:

class Post extends Eloquent
{
    public function parent()
    {
        return $this->belongsTo('Post', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('Post', 'parent_id');
    }
}

How can I make a Laravel Nova resource display this connection?

public function fields(Request $request)
{
    return [
        Text::make('Autor', 'author'),
        Select::make('Type', 'type')->options([
            'News' => 'news',
            'Update' => 'update',
        ]),
        BelongsToMany::make('Post') // does not work
    ];
}

Advertisement

Answer

You can achieve what you want like this:

BelongsTo::make('Parent', 'parent', AppNovaPost::class),

HasMany::make('Children', 'children', AppNovaPost::class),

This will allow to choose a parent post when you create or update a post. When you are in the detail page of a post, you can see all its children.

public function fields(Request $request)
{
    return [
        Text::make('Author', 'author'),
        Select::make('Type','type')->options([
            'News' => 'news',
            'Update' =>  'update',
        ]),
        BelongsTo::make('Parent', 'parent', AppNovaPost::class),
        HasMany::make('Children', 'children', AppNovaPost::class),
    ];
}

Note: Please note that the third param to BelongsTo::make() and HasMany::make() is a reference to the Post Resource, not Post model.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement