Change default primary key in Eloquent

Laravel 4Eloquent

Laravel 4 Problem Overview


Can I change Eloquent model primary key.

I want to set primary key for example admin_id instead of 'id'?

I know I can change table name for model like

protected $table = "admin";

Is there something similar for primary key?

Laravel 4 Solutions


Solution 1 - Laravel 4

Yes

class User extends Eloquent {

    protected $primaryKey = 'admin_id';

}

Solution 2 - Laravel 4

If you are wanting to use a composite key (a string)

You need to make sure you set public $incrementing = false otherwise laravel will cast the field to an Integer, giving 0

class User extends Model {

    protected $primaryKey = 'my_string_key';
    public $incrementing = false;

}

Solution 3 - Laravel 4

class User extends Eloquent {

    protected $primarykey = 'admin_id';

}

but

class User extends Eloquent {

    protected $primaryKey = 'admin_id';

}

note the letter K (capital) on the variable $primaryKey

Solution 4 - Laravel 4

The primary key variable is case sensitive and must be $primaryKey to work.

Example:

protected $primaryKey = 'your_primary_key_id';

Example within a Model class:

class User extends Eloquent {

    protected $primaryKey = 'your_primary_key_id';

}

Solution 5 - Laravel 4

class User extends Eloquent {

    protected $primaryKey = 'admin_id';

}

As per Laravel documentation :


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

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

Solution 6 - Laravel 4

To assign a primary key you should:

class User extends Eloquent {

    protected $primaryKey = 'admin_id';

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVuk StankovićView Question on Stackoverflow
Solution 1 - Laravel 4phirschybarView Answer on Stackoverflow
Solution 2 - Laravel 4Toby MellorView Answer on Stackoverflow
Solution 3 - Laravel 4user3186817View Answer on Stackoverflow
Solution 4 - Laravel 4ajtrichardsView Answer on Stackoverflow
Solution 5 - Laravel 4GammerView Answer on Stackoverflow
Solution 6 - Laravel 4Jay MomayaView Answer on Stackoverflow