Home > Software engineering >  Can I use AUTO_INCREMENT in my laravel project?
Can I use AUTO_INCREMENT in my laravel project?

Time:05-12

I have an Eloquent model that has a column that is a number composed of various codes and at the end a number that should increment automatically. This last number is the same number I use to define the primary key of my model, so my question is:

Is there a way to use the AUTO_INCREMENT variable from my MySQL database?

If not, what is the best way to create a variable in Laravel that automatically increments?

example:

$code1 = $this->getCode1();
$code2 = $this->getCode2();

$autoIncr = ...;

$final_code = $code1 . $code2 . $autoIncr;

CodePudding user response:

you can create a function that returns the next id (autoincrement) of your table and the insert the entry in your table;

$code1 = $this->getCode1();
$code2 = $this->getCode2();

$autoIncr = $this->getNextAutoincrement(); 

$final_code = $code1 . $code2 . $autoIncr; 

//Insert in your table
$row = YourModel::create([
   'finalCode' => $final_code
]);

private function getNextAutoincrement() {
    //don't forget import DB facade at the beginning of your class
    $id = DB::select("SHOW TABLE STATUS LIKE 'YOUR_TABLE_NAME'");
    $next_id=$id[0]->Auto_increment;
    return $next_id; 
}

Hope I've helped you

  • Related