Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
Javier Pozo Avatar asked Feb 24 '20 13:02

Javier Pozo


1 Answers

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');
});
like image 132
Nicklas Kevin Frank Avatar answered Sep 21 '22 21:09

Nicklas Kevin Frank