diff --git a/src/Illuminate/Database/Schema/Blueprint.php b/src/Illuminate/Database/Schema/Blueprint.php index 00fe7c55e086..74b584b51a68 100755 --- a/src/Illuminate/Database/Schema/Blueprint.php +++ b/src/Illuminate/Database/Schema/Blueprint.php @@ -5,6 +5,7 @@ use BadMethodCallException; use Closure; use Illuminate\Database\Connection; +use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Query\Expression; use Illuminate\Database\Schema\Grammars\Grammar; use Illuminate\Database\SQLiteConnection; @@ -938,9 +939,19 @@ public function foreignIdFor($model, $column = null) $model = new $model; } - return $model->getKeyType() === 'int' && $model->getIncrementing() - ? $this->foreignId($column ?: $model->getForeignKey()) - : $this->foreignUuid($column ?: $model->getForeignKey()); + $column = $column ?: $model->getForeignKey(); + + if ($model->getKeyType() === 'int' && $model->getIncrementing()) { + return $this->foreignId($column); + } + + $modelTraits = class_uses_recursive($model); + + if (in_array(HasUlids::class, $modelTraits, true)) { + return $this->foreignUlid($column); + } + + return $this->foreignUuid($column); } /** diff --git a/tests/Database/DatabaseSchemaBlueprintTest.php b/tests/Database/DatabaseSchemaBlueprintTest.php index 45a72191faa6..884434ddc642 100755 --- a/tests/Database/DatabaseSchemaBlueprintTest.php +++ b/tests/Database/DatabaseSchemaBlueprintTest.php @@ -372,6 +372,29 @@ public function testGenerateRelationshipColumnWithUuidModel() ], $blueprint->toSql($connection, new MySqlGrammar)); } + public function testGenerateRelationshipColumnWithUlidModel() + { + require_once __DIR__.'/stubs/EloquentModelUlidStub.php'; + + $base = new Blueprint('posts', function (Blueprint $table) { + $table->foreignIdFor('EloquentModelUlidStub'); + }); + + $connection = m::mock(Connection::class); + + $blueprint = clone $base; + + $this->assertEquals([ + 'alter table "posts" add column "eloquent_model_ulid_stub_id" char(26) not null', + ], $blueprint->toSql($connection, new PostgresGrammar)); + + $blueprint = clone $base; + + $this->assertEquals([ + 'alter table `posts` add `eloquent_model_ulid_stub_id` char(26) not null', + ], $blueprint->toSql($connection, new MySqlGrammar())); + } + public function testDropRelationshipColumnWithIncrementalModel() { $base = new Blueprint('posts', function ($table) { diff --git a/tests/Database/stubs/EloquentModelUlidStub.php b/tests/Database/stubs/EloquentModelUlidStub.php new file mode 100644 index 000000000000..f8f54a67d935 --- /dev/null +++ b/tests/Database/stubs/EloquentModelUlidStub.php @@ -0,0 +1,15 @@ +