Laravel Nova Polymorphic many-to-many relationship is not working

Viewed 2871

I am developing a Laravel admin dashboard using Laravel Nova. I am having an issue with using polymorphic many-to-many relationship. Following is my scenario.

I have the user table with this definition

class User extends Model
{
    public function sportsocieties()
    {
        return $this->morphedByMany(SportSociety::class, 'involvable', 'involvables', 'user_id', 'involvable_id');
    }

    public function dancersocieties()
    {
        return $this->morphedByMany(DancerSociety::class, 'involvable', 'involvables', 'user_id', 'involvable_id');
    }
}

This is the SportSociety model class

class SportSociety extends Model
{
    public function users()
    {
        return $this->morphToMany(User::class, 'involvable', 'involvables', 'involvable_id','user_id');
    }
}

This is DancerSociety model class

class DancerSociety extends Model
    {
        public function users()
        {
            return $this->morphToMany(User::class, 'involvable', 'involvables', 'involvable_id','user_id');
        }
    }

Then I created a migration to create the pivot table. This is the definition for the migration file.

class CreateInvolvablesTable extends Migration
{
    public function up()
    {
        Schema::create('involvables', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->unsignedInteger("user_id");
            $table->unsignedInteger("involvable_id");
            $table->string("involvable_type");
        });
    }
    public function down()
    {
        Schema::dropIfExists('involvables');
    }
}

From the Nova UI, when I attach a SportSociety or DancerSociety to a user, I got the following error message.

Field involvable_type does not have a default value. (SQL: insert into involvables (user_id, involvable_id) values (1, 5))

What is wrong with my polymorphic relationship? Or does Nova have issues with polymorphic relationships?

2 Answers

The problem was that I was not using the right field for the Nova. In the Nova, I was using BelongsToMany. Instead of that, I needed to use MorphToMany.

Field involvable_type does not have a default value. (SQL: insert into involvables (user_id, involvable_id) values (1, 5))

This error means that in the database this field does not have a default value ('', NULL, whataver you need), you simply must set it to nullable or pass a value.

Related