Eloquent fills the primary key with the value of last_inserted_id, that column needs to be auto increment. You have to change the trigger and add the logic to change the last_inserted_id to the new uuid() .
Eloquent does not able to catch custom primary key after save created by MySQL trigger
I have the following model with custom primary key, UUID value, created with MySQL trigger:
class Operation extends Model
{
protected $table = 'cavity_actions';
protected $primaryKey = 'aid'; // or null
public $incrementing = false;
}
In the controller when I try to save new model:
$op = new \App\Operation;
$op->cavity_id = request('cavity_id');
$op->....
$op->save();
dd($op->aid)
dd($op->aid) returns null inspite of that model is successfully saved to cavity_actions table with a UUID value generated for aid field using the MySQL trigger!
The following is the trigger code:
CREATE TRIGGER `before_insert_cavity_actions` BEFORE INSERT ON `cavity_actions`
FOR EACH ROW SET new.aid = uuid()
@agCepeda I have made another solution based on the last answer of the StackOverFlow question you have regarded.
I have modified the trigger to be like:
CCREATE TRIGGER `before_insert_cavity_actions` BEFORE INSERT ON `cavity_actions` FOR EACH ROW
IF new.aid IS NULL THEN
SET new.aid = uuid();
END IF
Then from the controller's action I have defined my own random identifier generator that generates the key value like the following:
$op->aid = str_pad(strtotime($dt),11,'-').\FoxRandStr::generate(4,'uln').'-'.\FoxRandStr::generate(20,'uln');
The above Identifier is 36 characters string with three portion, the first is the timestamp of the current date/time i.e $dt = date(Y-m-d H:i:s) paded with - to reach 11 charcters length, the second is four characters string of upper case, lower case and numbers string while the last is 20 characters with the same specifications like the the second portion.
Please or to participate in this conversation.