Javier Pozo
Javier Pozo

Reputation: 475

Laravel: Create morphs() relationship nullable

I want to create a one-to-one polymorphic relation allow null relation.

Example:

  Schema::create('ps_assistances', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('assistance_number', 50)->nullable();
            $table->morphs('assitanceable')->nullable();
  });

But this example return null when assing "->nullable()" to morph column.

I try to create _type and _id manually and it works fine.

Example with manually morph column:

  Schema::create('ps_assistances', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('assistance_number', 50)->nullable();
            $table->string('assitanceable_type')->nullable();
            $table->unsignedBigInteger('assitanceable_id')->nullable();
  });

I want to know if exists a better way to do a one-to-one polymorphic relation nullable.

Upvotes: 30

Views: 15132

Answers (2)

eylay
eylay

Reputation: 2160

You can use nullableMorphs

$table->nullableMorphs('assitanceable');

https://laravel.com/docs/9.x/migrations#column-method-nullableMorphs

Upvotes: 12

Nicklas Kevin Frank
Nicklas Kevin Frank

Reputation: 6337

nullableMorphs should handle this for you

e.g:

Schema::create('ps_assistances', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('assistance_number', 50)->nullable();
    $table->nullableMorphs('assitanceable');
});

Upvotes: 62

Related Questions