Get enity id with aftersave when using newEntities

I am wondering how I can get the id of each entity that gets saved when I use newEntities.

I use ajax to save an array of elements into the db.

In the controller:
public function addmenuitems() {
if ($this->request->is(‘ajax’)) {
$this->autoRender = false;
if ($this->request->is(‘post’)) {
$menuitemTable = TableRegistry::getTableLocator()->get(‘menuitems’);
$menuitems = $menuitemTable->newEntities($this->request->getData());
if ($menuitemTable->saveMany($menuitems)) {
$message = ‘Cool’;
$message = ‘Error’;

And in the Table.php file:
public function afterSave($event, $entity) {
return $entity;

But I don’t get any response other than: ‘Success’.

How can I return each id?

You can use saveMany result like:

$result = $menuitemTable->saveMany($menuitems);
foreach ($result as $item){
echo $item->id;