Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    ];
}
like image 217
Mister Verleg Avatar asked Dec 03 '18 14:12

Mister Verleg


2 Answers

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.

like image 135
Chin Leung Avatar answered Sep 28 '22 10:09

Chin Leung


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)

like image 20
Prafulla Kumar Sahu Avatar answered Sep 28 '22 08:09

Prafulla Kumar Sahu