CakePHP 4 Delete Table Row Using Model And Entity

Reading Time: 4 minutes
1,768 Views

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

There are several ways to delete 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 delete 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 deleteProduct()
    {
        $product_id = 101;

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

        $queryObject->delete()->where([
            "id" => $product_id
        ])->execute();
    }
}

Method #1

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

public function deleteProduct()
{
    $product_id = 101;

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

    $queryObject->delete()->where([
        "id" => $product_id
    ])
    ->execute();
}

Method #2

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

public function deleteProduct()
{
    $product_id = 101;

    $productEntity = $this->Products->get($product_id);

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

So, here we can see we have these above options by which we can delete row from 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 Delete Table Row Using Model And Entity Tutorial in a very detailed way.

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.