Laravel Eloquent Change primary key and timestamps


Example

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.

class Citizen extends Model
{
    protected $primaryKey = 'socialSecurityNo';

    // ...
}

Now, any Eloquent methods that use your primary key (e.g. find or findOrFail) will use this new name.

Additionally, Eloquent expects the primary key to be an auto-incrementing integer. If your primary key is not an auto-incrementing integer (e.g. a GUID), you need to tell Eloquent by updating the $incrementing property to false:

class Citizen extends Model
{
    protected $primaryKey = 'socialSecurityNo';

    public $incrementing = false;

    // ...
}

By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the $timestamps property on your model to false:

class Citizen extends Model
{
    public $timestamps = false;

    // ...
}

If you need to customize the names of the columns used to store the timestamps, you may set the CREATED_AT and UPDATED_AT constants in your model:

class Citizen extends Model
{
    const CREATED_AT = 'date_of_creation';
    const UPDATED_AT = 'date_of_last_update';

    // ...
}