In Laravel Nova I have BelongsToMany Relationship (companies - pivot - requests).
In the Pivot table I have some additional columns which I access with the pivot fields (https://nova.laravel.com/docs/1.0/resources/relationships.html#belongstomany) which works great.
But now I have a special case where I have an additional BelongsTo relationship from the pivot table to a third table (states). I tried to define a BelongsTo Field in the pivot Fields, but that is not working.
BelongsToMany::make('Companies', 'companies', Company::class)->fields(new CompanyRequestFields()),
pivot fields:
class CompanyRequestFields
{
/**
* Get the pivot fields for the relationship.
*
* @return array
*/
public function __invoke()
{
return [
Number::make('preis'),
Text::make('bezahlt'),
BelongsTo::make('State', 'state', States::class),
];
}
}
The error I get:
Call to undefined method Illuminate\Database\Eloquent\Relations\Pivot::state()
The relationship state() actually exists on the pivot Model and there is a Nova resource State class too.
So it looks like this is not supported from PivotFields? Or does anyone know if its possible to accomplish this?
I was not able to make it work with relationship in pivot table, but you can achieve it without a relationship definition like below.
class CompanyRequestFields
{
public function __invoke()
{
$states= \App\State::all()->pluck('name', 'id');
return [
...
Select::make('State')->options($states),
];
}
}
In \App\Request
model
public function companies()
{
return $this->belongsToMany('App\Company')->withPivot('state');
}
Hope this approach will help you.
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