12

Name of the primary key column in any model in Laravel framework is id

protected $primaryKey = 'id';

And I know I can change that default name like this:

protected $primaryKey = 'new_name';

My question is: What if I have a composite key (2 or more columns) in the table, how do I add them as the $primaryKey? And do I really have to define them?

Amr
  • 4,809
  • 6
  • 46
  • 60
  • Possible duplicate of [How I can put composite keys in models in Laravel 5?](https://stackoverflow.com/questions/31415213/how-i-can-put-composite-keys-in-models-in-laravel-5) – mopo922 Jan 05 '18 at 02:45

1 Answers1

8

From the Laravel docs:

$table->primary(array('first', 'last'));

Edit: I misunderstood the question. This thread might provide some answers: http://forumsarchive.laravel.io/viewtopic.php?pid=34475

Specifically overriding the find() method.

public static function find($primaryOne, $PrimaryTwo) {
    return Widget::where('primaryOne', '=', $primaryOne)
        ->where('PrimaryTwo', '=', $PrimaryTwo)
        ->first();
} 
Michael Lawton
  • 1,460
  • 1
  • 14
  • 25
  • `$table->primary(array('first', 'last'))` usually used in the migration file while creating the table, I'm asking for `protected $primaryKey = 'id'` that exists in the related model file. – Amr May 24 '15 at 23:58
  • 1
    I'm in a bit over my head here but it doesn't look like Laravel supports that by default. – Michael Lawton May 25 '15 at 00:02
  • where this find method exist to override ? In my model class no such method to override. – Prasad Lakmal Nov 12 '15 at 20:50