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
];
}
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With