← Back to all snippets
PHP

Customize Eloquent Model Table and Primary Key

Override default table name and primary key conventions for Laravel Eloquent models, essential for integrating with legacy databases or specific naming schemes.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class LegacyUser extends Model
{
    /**
     * The table associated with the model.
     * If not set, Eloquent assumes 'legacy_users'.
     * @var string
     */
    protected $table = 'old_users_table';

    /**
     * The primary key for the model.
     * If not set, Eloquent assumes 'id'.
     * @var string
     */
    protected $primaryKey = 'user_id';

    /**
     * Indicates if the IDs are auto-incrementing.
     * If the primary key is a UUID or a custom string, set to false.
     * @var bool
     */
    public $incrementing = false;

    /**
     * The "type" of the primary key ID.
     * Can be 'int', 'string', etc. Essential if not auto-incrementing.
     * @var string
     */
    protected $keyType = 'string';

    /**
     * Indicates if the model should be timestamped.
     * Set to false if 'created_at' and 'updated_at' columns do not exist.
     * @var bool
     */
    public $timestamps = false;
}
How it works: By default, Eloquent assumes that your model's table name is the plural, snake_case version of the model name (e.g., `User` -> `users`) and that the primary key is an auto-incrementing integer column named `id`. However, you can easily customize these conventions using the `$table`, `$primaryKey`, `$incrementing`, `$keyType`, and `$timestamps` properties within your model class, which is crucial when working with existing or legacy database schemas.

Need help integrating this into your project?

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

Hire DigitalCodeLabs