In this post, you will learn how to disable primary key and auto increment in laravel Model.
Auto Increment and primary key are good option for generating unique number id but something it is not required.
Following this tutorial, you will learn how to disable primary key & auto increment in laravel.
Also this tutorial is validate for laravel 6, laravel 7, laravel 8 and laravel 9 as well.
Table of Contents
Assumption
Let’s assume we have Article
Model which is tied to the article
the table which has the following columns:
- id
- title
- content
- category
- created_at
- updated_at
[also_read href=”https://impulsivecode.com/laravel-crud-tutorial-example-for-beginners/” title=”Laravel 9 Todo App CRUD Tutorial”]
How to Disable Primary Key & Auto Increment in Laravel?
To disable the primary key and auto increment in the laravel, laravel provides us $primaryKey
and $incrementing
variable in the model.
Here is how to do it in the model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
protected $primaryKey = null;
public $incrementing = false;
protected $fillable = [
'title', 'content','category'
];
}
In the above code, we have protected $primaryKey = null
variable to disable primary key and public $incrementing = false;
in order to disable the autoincrementing.
So now if we add the article, the primary key and auto increment will not get updated.
Conclusion:
Great, so in the above tutorial, you have learned how to disable primary key and auto increment in laravel Model.
See you in the next tutorial.
Write a Reply or Comment