1

I set 'username' column as primary key in phpmyadmin, but didn't set it in User model, why is it the model never treat username as primary key in laravel?

hahahaha
  • 1,013
  • 2
  • 14
  • 41

2 Answers2

2

Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.

Hiren Makwana
  • 1,976
  • 2
  • 13
  • 28
1

In your Model define your custom primary key as below:

protected $primaryKey = "username";
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53
  • must i do this? i already set the username in phpmyadmin as primary key. – hahahaha Jun 13 '16 at 09:39
  • 1
    yes, In laravel field id set as primary key , if you want to define your own primary key ,you must define it as above. – Yasin Patel Jun 13 '16 at 09:41
  • Yes. The Eloquent / Doctrine DBAL can read from the database, but it does not retrieve table information. You have to set Model fields manually when you want special metadata applying. For example, `protected $primaryKey` will treat a column as the primary key. `protected $dates` will mutate the DateTime/Timestamp fields you pass as an array. For more information: https://laravel.com/docs/5.2/eloquent#eloquent-model-conventions – Justin Origin Broadband Jun 13 '16 at 09:42
  • but if i change the data structure from phpmyadmin eg: from int to string, laravel will return error right? – hahahaha Jun 13 '16 at 09:45
  • This may be what you were looking for. Related: "using a string as a primary key". Handy if you're using things like UUID http://stackoverflow.com/questions/34582535/laravel-5-2-use-a-string-as-a-custom-primary-key-for-eloquent-table-becomes-0 – Justin Origin Broadband Jun 13 '16 at 09:50
  • laravel detects column structure changes but couldn't detect which column is primary key? – hahahaha Jun 13 '16 at 10:31
  • 1
    If you change in column structure in database you need to refresh migration and laravel couldn't detect which column is primary key. – Yasin Patel Jun 13 '16 at 11:09