2

For auto increment id with int, after save() method, it returns id.

But it does not return custom increment id primary key done by mysql trigger.

$productData = new Product($request->all());
$productData->save($productData->getAttributes());
return $productData->id;

how to retrieve custom id in this case ?

Aung
  • 65
  • 1
  • 13

2 Answers2

0

You need to refresh the model instance. To illustrate:

$p = (new Product($request->all()))->save();
return $p->fresh()->id;
  • I tried $productData->fresh()->id but $productData->fresh() only returns null value – Aung Jan 22 '18 at 12:05
0

This is beyond laravel, as auto incremented field is provided by your database and laravel could not get the last_insert_id from your DB.

For this case you have to change your trigger such that it change last_insert_id with the new value:

Is there a way to get last inserted id of a NON - auto incremented column in MySQL?

Note: You might need to make sure Model's incrementing is true so that it will try to fetch the id from database. If you have not set this field in your Model, then don't set it. By default Model is capable in getting the value from your database automatically after an insert.

Lionel Chan
  • 7,894
  • 5
  • 40
  • 69
  • I set incrementing is false because return id only 0 if incrementing is true. I also set new id as ' SET New.id = function for custom id ' in trigger before insert. – Aung Jan 31 '18 at 09:29
  • as a work around, i think i should just add a new custom primary key field instead of customize auto increment id field. thank :) – Aung Jan 31 '18 at 09:33
  • Ah okay. Sorry that's based on code analyzing. Not too sure why it doesn't work that way! – Lionel Chan Jan 31 '18 at 10:37