Inside this tutorial we will see CakePHP 4 Insert Table Row using model and entity. We will use the concept of Model and entity of CakePHP and see how to insert a table row. Article contains classified information about this insert concept.
There are several ways to insert 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 insert a new row into it.
Learn More –
- CakePHP 4 Custom Validation Rule For Form Inputs
- CakePHP 4 Database Seeding From CSV File Tutorial
- CakePHP 4 Database Seeding From JSON File Tutorial
- CakePHP 4 Database Seeding Using Faker Library
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.
Next,
To use model into controller we need to load it first.
$this->loadModel("Products");
Let’s see the complete code of controller –
<?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 addProduct()
{
$queryObject = $this->Products->query();
$queryObject->insert(["name", "cost", "description", "status"])
->values([
"name" => "Sample Product 1003",
"cost" => 800,
"description" => "Sample product content",
"status" => 1
])
->execute();
}
}
Method #1
To insert data into database table we can see this concept. Here only model has been used to insert.
public function addProduct()
{
$queryObject = $this->Products->query();
$queryObject->insert(["name", "cost", "description", "status"])
->values([
"name" => "Sample Product 1003",
"cost" => 800,
"description" => "Sample product content",
"status" => 1
])
->execute();
}
We have also two more ways to insert data.
Method #2
Insert row using Model and Entity, we use this code.
public function addProduct()
{
$productEntity = $this->Products->newEmptyEntity();
$productEntity->name = "Sample Product 1001";
$productEntity->cost = 500;
$productEntity->description = "Sample Product content";
$productEntity->status = 1;
$this->Products->save($productEntity);
}
Method #3
Insert row using Model and Entity, again we can use this code.
public function addProduct()
{
$productEntity = $this->Products->newEmptyEntity();
$product_data = [
"name" => "Sample Product 1002",
"cost" => 750,
"description" => "Sample product content",
"status" => 1
];
$productEntity = $this->Products->patchEntity($productEntity, $product_data);
$this->Products->save($productEntity);
}
So, here we can see we have these above options by which we can insert 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 Insert 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.
Read more