16

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?

2
  • @Strawberry - does that mean I need to define an integer id??? Jul 24, 2014 at 23:28
  • If you want to use Laravel, then I suspect you need to do whatever Laravel tells you to do!
    – Strawberry
    Jul 24, 2014 at 23:32

2 Answers 2

21

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();
    // ...
});
1
  • And this clears up the issue with returning 0 for models where the protected $primaryKey = 'slug'; Sep 22, 2017 at 22:15
3

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.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.