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?
A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.
Essentially, primary and foreign keys are used as a way to constrain or link related data in a database. This ensures that data remains consistent and that the database contains no redundant data. For example, if you delete a table (or even a row in a table) that other tables rely on, the redundant data is removed.
By default, eloquent assume that each model has a primary key column named id. But if you need to change the primary key with your own custom column name you can change it using the protected $primaryKey a property on your model.
By default, Eloquent models expect for the primary key to be named 'id' . If that is not your case, you can change the name of your primary key by specifying the $primaryKey property.
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();
// ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With