Table of contents
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';
}
Â
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;
}
Â
Â
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;
}
Â
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';
}
Â
Now you have ideas already on how to change your Laravel model primary keys and timestamps.
Â
I hope it helps :)
Read next