I need an effective way to disable Laravel from auto incriminating the primary key of the table which I am going to insert data in.
Why? I don't check if there is any duplication between the DB and the inserted data so if there was any duplication I just handles it in a try-catch block.
The problem is if there was any failure Laravel counts it like I have inserted a row. So IDs column is not going to be in this order [1, 2, 3, etc], but in this [1, 4, 8, 20, etc].
I searched a lot about this issue and I have tried to use this line after the declaration of the class:
public $autoincrement = false;
Also
public $incrementing = false;
But they are not working.
I just want to use the AI of my DB. Not Laravel's one.
if you wish to use a
non-incrementing or a non-numeric primary key
you mustset the public $incrementing property
on your model tofalse
.eg :
in case of migration :
refer : https://laravel.com/docs/5.3/eloquent#eloquent-model-conventions
Try
public $incrementing = false;
You can do something like below
Table: author
Columns: id, name, active
Here in fillable you define the columns that you want to change or update through model. Rest fields behaviour will take according to mysql definition.
I hope this will help you.
You have to declare your new primary key in your table migration file:
Of course you have to disable autoincrement in your model as you did.
This is an example for table created its name site_rules and this is the migration file which i add the following line to make id primary and auto incremented
//add this line to make id auto incremented from a specified value DB::statement("ALTER TABLE site_rules AUTO_INCREMENT = 1;");
and this is the migration file code :Try it
There are 2 solutions to your problem. First one is, as you said, disable the increment column. To do that, just go to your migrations, and change
$table->increment('id
)`to
$table->integer('id')
It will remove the primary key, to set the primary key, just go to your Model file and add this:
Second solution is what I prefer. Whenever inserting, updating or removing a record and even sometimes reading a record, use laravel's DB transaction. Here is an example:
This approach is better than remove the auto increment. But now it's upto you to choose.