CakePHP 4 Update Table Row Using Model And Entity

Reading Time: 5 minutes
3,786 Views

Inside this tutorial we will see CakePHP 4 Update Table Row using model and entity. We will use the concept of Model and entity of CakePHP and see how to update a existing table row. Article contains classified information about this update concept.

There are several ways to update data into database table – Using Query Builder, Using Model & Entity, etc.

Suppose we have a table called products into database. Table products have these columns – ( id, name, cost, description, status ). We will create model and entity for this table and see how to update a row from it.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE mydatabase;

Successfully, we have created a database.

Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –

//...

'Datasources' => [
        'default' => [
            'host' => 'localhost',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',

            'username' => 'root',
            'password' => 'sample@123',

            'database' => 'mydatabase',
            /*
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
             */
            //'schema' => 'myapp',

            /*
             * You can use a DSN string to set the entire configuration
             */
            'url' => env('DATABASE_URL', null),
        ],
  
     //...

//...

You can pass host, username, password and database.

Successfully, you are now connected with the database.

Create Model & Entity

Open project into terminal and run this bake console command –

$ bin/cake bake model Products --no-rules --no-validation

It will create several files like Model, Entity, Test & Fixture.

Model class file ProductsTable.php is inside /src/Model/Table folder. Entity class file Product.php is inside /src/Model/Entity folder.

Code for Model class file.

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class ProductsTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('products');
        $this->setPrimaryKey('id');
    }
}

Code for Entity class file.

<?php
declare(strict_types=1);

namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * Product Entity
 *
 * @property int $id
 */
class Product extends Entity
{
    protected $_accessible = [
        'name' => true,
        'cost' => true,
        'description' => true,
        'status' => true,
    ];
}

Create Controller

To create controller we will use bake console command –

$ bin/cake bake controller Sites --no-actions

It will create a file SitesController.php inside /src/Controller folder.

<?php

declare(strict_types=1);

namespace App\Controller;

class SitesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel("Products");
        $this->autoRender = false;
    }

    public function updateProduct()
    {
        $product_id = 10;

        $queryObject = $this->Products->query();

        $queryObject->update()->set([
            "name" => "New Product Name",
            "cost" => 800
        ])
        ->where([
            "id" => $product_id
        ])
        ->execute();
    }
}

Method #1

To update data into database table we can see this concept. Here only model has been used to update.

public function updateProduct()
{
    $product_id = 10;

    $queryObject = $this->Products->query();

    $queryObject->update()->set([
        "name" => "New Product Name",
        "cost" => 800
    ])
    ->where([
        "id" => $product_id
    ])
    ->execute();
}

We have also two more ways to update data.

Method #2

Update row using Model and Entity, we use this code.

public function updateProduct()
{
    $productEntity = $this->Products->get($product_id);

    $product_data = [
        "name" => "New Product Name",
        "cost" => 800
    ];

    $productEntity = $this->Products->patchEntity($productEntity, $product_data);

    $this->Products->save($productEntity);
}

Method #3

Update row using Model and Entity, again we can use this code.

public function updateProduct()
{
    $productEntity = $this->Products->get($product_id);

    $productEntity->name = "New Product Name";
    $productEntity->cost = 800;

    $this->Products->save($productEntity);
}

So, here we can see we have these above options by which we can update row into database table. This is only using model and entity. Query builder is a different way than this.

We hope this article helped you to learn about CakePHP 4 Update Table Row Using Model And Entity Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.