Search code examples
laraveleloquentlaravel-nova

Laravel Nova show Many-to-Many with pivot


I have two tables show_types and venues. With a many-to-many relationship i did create a new pivot as follows

public function up()
{
    Schema::create('show_types_venues', function (Blueprint $table) {
        $table->integer('show_types_id')->unsigned();
        $table->foreign('show_types_id')->references('id')->on('show_types');

        $table->integer('venue_id')->unsigned();
        $table->foreign('venue_id')->references('id')->on('venues');
    });
}

And added to the models

ShowType.php
    public function venues()
    {
        return $this->belongsToMany(Venue::class, 'show_types_venues', 'show_types_id', 'venue_id');
    }


Venue.php
    public function shows()
    {
        return $this->belongsToMany(ShowType::class, 'show_types_venues', 'venue_id', 'show_types_id');
    }

I'm trying to make this relation show up on Nova using

ShowType.php
 public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Text::make('Name'),
            BelongsToMany::make('Venues', 'venues', Venue::class)
        ];

But nothing shows up in my interface. How can i make it show a select multiple where I could add/edit the venues associated with this showType? Do i need to create something more "manual" ? Thanks


Solution

  • Without luck with the documentation of Nova, I did a workaround using Bejacho's Belongs to Many Fields in which we can easily add the many to many relationships appearing as a multiple selector on Nova. Having the same setup as i mentioned above the only thing i did was to follow their example:

    use Benjacho\BelongsToManyField\BelongsToManyField;
    
    public function fields(Request $request){
        return [
            ..., //If you are using with BelongsToMany native Field, put this field after
    
            BelongsToManyField::make('Role Label', 'roles', 'App\Nova\Role'),
        ];
    }
    

    And worked perfectly for what I needed!