Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel nova BelongsToMany - BelongsTo in pivot

Tags:

laravel-nova

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?

like image 938
ndberg Avatar asked Nov 27 '22 00:11

ndberg


1 Answers

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.

like image 102
Saumini Navaratnam Avatar answered Dec 30 '22 21:12

Saumini Navaratnam