Reputation: 40633
I'm trying to set a string column as a primary key of a table, then reference that from another table as a foreign key. Is this possible? Per the documentation:
Laravel assumes every table has a numeric primary key (usually named “id”) and ensures the value of this column is unique for each new row added to the table. Laravel doesn’t really work well unless each table has a numeric primary key. So, for your average Laravel application, please ensure that you define a primary key using the increments() method.
In my case, I don't want to define an id
column as it would be useless. The string column I want to define will act as a primary key. If this is possible, can I get an example migration snippet?
Upvotes: 16
Views: 5693
Reputation: 5406
This is an old question, but for the sake of correctness I'd like to point out that in the current versions of Eloquent you can indeed use non numeric primary/foreign keys.
One thing you need to do is to set the property $incrementing
to false
on the models that use non autoincrementing ids.
class Employee extends Model
{
public $incrementing = false;
// ...
}
also, the migration can be something like this:
Schema::create('employees', function (Blueprint $table) {
$table->string('id')->primary();
// ...
});
Upvotes: 22
Reputation: 3374
More details why it cannot be string in Eloquent may be found in this forum archive.
Also, to the comment: Eloquent conforms the normalization rules. Althought, SQL supports foreign keys to be strings or integers without difference, you should consider adding an integer format keys to your application to make use of Eloquent, that is using generally accepted integer keys.
Upvotes: 3