Mister Verleg
Mister Verleg

Reputation: 4303

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
    ];
}

Upvotes: 7

Views: 5052

Answers (3)

Hassan Elshazly Eida
Hassan Elshazly Eida

Reputation: 839

make sure to have title in your resource that represent the display name

class Post extends Resource
{
       public static $title = 'name';
}

Upvotes: 0

Chin Leung
Chin Leung

Reputation: 14921

You can achieve what you want like this:

BelongsTo::make('Parent', 'parent', \App\Nova\Post::class),

HasMany::make('Children', 'children', \App\Nova\Post::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', \App\Nova\Post::class),
        HasMany::make('Children', 'children', \App\Nova\Post::class),
    ];
}

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

Upvotes: 11

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9693

There is another situation, where you will find same issue, if you have parent column name parent and also relationship parent like

$table->bigIncrements('id');
$table->string('category');
$table->unsignedBigInteger('parent')->nullable();

and In model

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

It will be unable to recognize the parent property and you will face this problem again, in that case, you can change the relationship name or column name, and it will work fine.

Also remember the arguments for Nova BelongsTo relationship

Argument 1. Name to display (e.g. Parent)

Argument 2. Name of the relationship as used in the model (e.g. parent)

Argument 3. The Nova Resource (e.g. App\Nova\Category)

Upvotes: 3

Related Questions