How can i get last insert id, look like this :
$user = new User();
$user->name = 'asdf';
$user->save();
echo $user->id;
But inside models in function aftercreate
or beforecreate
function :
public function beforecreate(){
// last id ?
}
What I'm trying to do is to logs the sql statement into another table.
You could do this in the afterCreate. Please note the exit;
for debugging purpose.
public function afterCreate()
{
echo $this->id; // 8
exit;
}
Unfortunately you can not access the id in beforeCreate because the record is not yet created, thus there is no id yet.
If you really need id in beforeCreate you could try to get current max value of the primary key and increment it with 1. But that's a bit hacky and using afterCreate is the preferred option.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments