How to add primary key to Laravel model?


If you did not specify primary key in your model, laravel will assume the primary key of the table is 'id', so for example your primary key is not 'id', but let's say 'user_id' or 'employee_id' etc, how to define this in the model?

On the model, you can specify the table using variable named $table, to specify primary key you can use variable named $primaryKey (with capital letter K).

Here's an example of model Car (car.php), this model has primary key 'car_id' instead of just 'id'.
class Car extends Eloquent {
  protected $table = 'cars';
  protected $primaryKey = 'car_id'; 
}

So what if i have more than one primary key (composite keys), well laravel doesn't support composite keys, but you can use this method as work around, simply use array on the $primaryKey variable.
$primaryKey = array('key1', 'key1');

I hope this short article is helpful



~ cheers ~


EmoticonEmoticon