Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Duplicate Save to Associated Table

Asyraf Wahi Anuar Updated 2 min read

Saving and duplicating data into the associated table? This quick tutorial will show how to save data and duplicate it into the associated table. For this tutorial, I set 2 tables, i) users and ii) clones where the input process will be executed in the table users and duplicate into table clones.

This tutorial may be outdated

It was last reviewed 4 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

Saving and duplicating data into the associated table? This quick tutorial will show how to save data and duplicate it into the associated table. For this tutorial, I set 2 tables, i) users and ii) clones where the input process will be executed in the table users and duplicate into table clones.

The Tables

Table: users

HTML
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| fullname | varchar(255) | NO   |     | NULL    |                |
| email    | varchar(255) | NO   |     | NULL    |                |
| gender   | int(1)       | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

Table: clones

HTML
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_id  | int(11)      | NO   |     | NULL    |                |
| fullname | varchar(255) | NO   |     | NULL    |                |
| email    | varchar(255) | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

Save and Duplicate

In this tutorial, the table users are associated with table clones. The idea is to save the input data from table users into table clones together with the user_id. To ensure that we capture the user_id into the table clones, we need to execute the associated save after users save method.

PHP
use Cake\ORM\TableRegistry; //add this at the beginning of the controller
public function add()
{
    $user = $this->Users->newEmptyEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());
        if ($this->Users->save($user)) {
            //save clone
            $clonesTable = TableRegistry::getTableLocator()->get('Clones');
            $cloneData = [
                'fullname' => $this->request->getData('fullname'),
                'email' => $this->request->getData('email'),
                'user_id' => $user->id,
            ];
            $clone = $clonesTable->newEntity($cloneData);
            $clonesTable->save($clone);

            $this->Flash->success(__('The user and clone has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
    $this->set(compact('user'));
}

If we assume that the clones table is not related to table users, then you can duplicate the data using the following codes (before user save or also can use above method):

PHP
use Cake\ORM\TableRegistry; //add this at the beginning of the controller
public function add()
{
    $user = $this->Users->newEmptyEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());
            $clonesTable = TableRegistry::getTableLocator()->get('Clones');
            $cloneData = [
                'fullname' => $this->request->getData('fullname'),
                'email' => $this->request->getData('email'),
            ];
            $clone = $clonesTable->newEntity($cloneData);
        
        if ($this->Users->save($user) && $clonesTable->save($clone)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
    $this->set(compact('user'));
}

That's all. Happy coding :)

Did this tutorial help?

216 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

Using Bahasa Melayu Table Names in CakePHP

Learn how to use Bahasa Melayu table names like "pengguna" in CakePHP while following the framework’s naming conventions. Includes tips for using the Bake tool and avoiding pluralization issues.

5 min read

Tools & Software

Formatting PHP in VSCode Using Prettier and PHP Intelephense

Learn how to set up Visual Studio Code (VSCode) for automatic PHP file formatting using the Prettier and PHP Intelephense extensions. This step-by-step tutorial will help you maintain a clean and organised codebase, enhancing your PHP development experience.

2 min read