DEV Community

Cover image for Change Primary Key and Timestamps in Laravel 8
Code And Deploy
Code And Deploy

Posted on

Change Primary Key and Timestamps in Laravel 8

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/change-primary-key-and-timestamps-in-laravel-8

By default, eloquent assume that each model has a primary key column named id. But if you need to change the primary key with your own custom column name you can change it using the protected $primaryKey a property on your model.

See the below example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'employee_id';
}
Enter fullscreen mode Exit fullscreen mode

Additionally, Eloquent assumes that the primary key is an auto-increment integer. But if your primary key is not auto-increment like if you are using UUID then you need to change your Eloquent $incrementing property to false.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'employee_id';

    /**
     * Indicates if the model's ID is auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;
}
Enter fullscreen mode Exit fullscreen mode

By default, Eloquent assumes created_at and updated_at columns exist on your tables. But if you want to not manage these by Eloquent, set the $timestamps property on your model to false.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;
}
Enter fullscreen mode Exit fullscreen mode

If your project database used another framework previously. And want to use the Laravel framework luckily we don't need to rename your created_at and updated_at columns you just define it with your current column names to the model.

See the below example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    const CREATED_AT = 'last_created';
    const UPDATED_AT = 'last_updated';
}
Enter fullscreen mode Exit fullscreen mode

Now you have ideas already on how to change your Laravel model primary keys and timestamps. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/change-primary-key-and-timestamps-in-laravel-8 if you want to download this code.

Happy coding :)

Top comments (0)