Home > Mobile >  How can I retrieve the id generated by a MySQL Trigger using a model with Laravel?
How can I retrieve the id generated by a MySQL Trigger using a model with Laravel?

Time:06-24

I am using a Trigger in MySQL to generate the id of a table instead of using an autoincrement field. The reason is because the id must have a check digit which is calculated when it’s inserted, based on the last id on the table.

The problem is that when I use $model->save() I don’t get the id generated and saved, as I get when using autoincrement fields. It always returns “0”.

Is there any way to retrieve the actual id that is saved in the database in this case?

CodePudding user response:

I assume your trigger is configured as AFTER INSERT ON. The reason you're getting the id 0 is that the INSERT command and the TRIGGER execution are 2 different DB transactions and id column is set to 0 as default. I haven't tested it but try to get the id with MySql PDO object.

$id = DB::getPdo()->lastInsertId();

And if it doesn't work. Just get the last inserted model.

$id = Model::latest()->first()->id;

There may be a better solution.

CodePudding user response:

Use laravel model refresh:

$model->refresh()

after saving to DB. You'll have the whole model there.

  • Related