PHP

Customizing Eloquent Model Primary Keys, Timestamps, and Table Names

Discover how to override default conventions for primary keys, timestamps, and table names in Laravel Eloquent models for greater database flexibility.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CustomModel extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_custom_table';

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'custom_id';

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The data type of the primary key.
     *
     * @var string
     */
    protected $keyType = 'string';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'creation_date';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'last_update';
}

// Example usage for setting custom timestamps if 'timestamps' is true
class AnotherModel extends Model
{
    protected $table = 'other_items';

    const CREATED_AT = 'created_on';
    const UPDATED_AT = 'updated_on';
}
How it works: Laravel Eloquent models follow conventions like using pluralized class names for table names, `id` for primary keys, and `created_at`/`updated_at` for timestamps. This snippet demonstrates how to customize these defaults. You can set `$table` to specify a custom table name, `$primaryKey` for a different primary key column, and `$incrementing` or `$keyType` for non-integer or non-auto-incrementing keys. By setting `$timestamps = false`, you disable Eloquent's automatic timestamp management. If timestamps are enabled but have different column names, you can define `CREATED_AT` and `UPDATED_AT` constants.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs