Gagzzz Gagzzz - 6 months ago 52
PHP Question

Hw can I get last inserted id in cakephp 3.x?

I am trying to get last inserted id in cake php 3.

if($this->request->is('post')){

$this->loadModel('MyPlaylists');

$playlistData = [];
$playlistData["user_id"] = $_POST['user_id'];
$playlistData["play_list_name"] = $_POST['play_list_name'];
$playlistData["section"] = $_POST['section'];
$playlistData["created"] = date('Y-m-d H:i:s', strtotime('now'));
$playlistData["status"] = 'active';
$playlist_en = $this->MyPlaylists->newEntity();
$this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$this->MyPlaylists->save($playlist_en);
$id=$this->MyPlaylists->id;
}


I have also tried:

$id=$this->MyPlaylists->lastInsertedId;


But it is giving error as below screenshot:
enter image description here

Answer Source

Your code needs some fine tuning.

$playlist_en    =    $this->MyPlaylists->newEntity();  
$playlist_en    =    $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$isValid        =    $this->MyPlaylists->save($playlist_en);
if ($isValid) {
    $id    =    $playlist_en->id;
    debug($id); // Check your last insert id
} else {
    pr($playlist_en->errors()); // Check errors
}