'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.
Solution 1:[1]
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');
});
Solution 2:[2]
You can use nullableMorphs
$table->nullableMorphs('assitanceable');
https://laravel.com/docs/9.x/migrations#column-method-nullableMorphs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nicklas Kevin Frank |
Solution 2 | eylay |