CodeIgniter 4 - React JS CRUD with MySQL Example Tutorial

Apr 19, 2022 . Admin


Hi Dev,

Here, I will show you how to works codeigniter 4 react crud. you'll learn codeigniter 4 react js crud. This tutorial will give you simple example of react js crud example with database. this example will help you codeigniter 4 crud operations with mysql an react.

This article is focused on Today. step by step explain In this tutorial I will share with you how to perform crud operation with react js in codeigniter 4. it's simple example of We will perform crud operation like create read update delete operation in codeigniter 4 with React Js. if you have question about codeigniter 4 with react js crud then I will give simple example with solution. you will do the following things for codeigniter 4 react js crud example.

How to engender CRUD operation with CodeIgniter 4 and React JS, CRUD is rudimental step of any core language framework. CRUD stands for Engender Read Update and Efface. So In this blog we will learn you insert update and efface in codeigniter 4.

if you want to create CRUD operation in CodeIgniter 4, There are listed bellow step you have to follow:

Step 1: Install Codeigniter 4

This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news

After Download successfully, extract clean new Codeigniter 4 application.

Step 2 : Basic Configurations

In this step we will now set basic configuration on the app/config/app.php file, so let’s implement to application/config/config.php and open this file on text editor.

app/config/app.php
public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';
Step 3 : Create Database and Table
CREATE TABLE `product` (
    `id` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL AUTO_INCREMENT,
    `name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
    `price` double COLLATE utf8mb4_unicode_ci NOT NULL,
    `sale_price` double COLLATE utf8mb4_unicode_ci NOT NULL,
    `sales_count` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL,
    `sale_date` VARCHAR(20) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
 
insert into product(id,name,price,sale_price,sales_count,sale_date) values(1, 'Desktop','30000','35000','55','02-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(2, 'Desktop','30300','37030','43','03-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(3, 'Tablet','39010','48700','145','04-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(4, 'Phone','15000','17505','251','05-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(5, 'Phone','18000','22080','178','05-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(6, 'Tablet','30500','34040','58','05-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(7, 'Adapter','2000','2500','68','06-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(8, 'TV','45871','55894','165','07-04-2018');

After create database and table successfully, we have to configuration of database in our Codeigniter 4 application, so open database.php file and add your database name, username and password.

Step 4 : Database Configurations application/config/database.php
public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];
Step 5 : Create Model app/Models/ProductModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
 
class ProductModel extends Model {
 
    protected $table      = 'product';
    protected $primaryKey = 'id';
     
    protected $returnType     = 'array';
 
    protected $allowedFields = ['name', 'price', 'sale_price', 'sales_count', 'sale_date'];
 
    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;
     
}
Step 6 : Create Controller

Here we go to app/Controllers and create a controller name Product.php. In this controller, you need to add the following methods into it:

app/controller/Product.php
<?php
namespace App\Controllers;
 
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\HTTP\RequestInterface;
 
class Product extends ResourceController {
     
    protected $modelName = 'App\Models\ProductModel';
    protected $format    = 'json';
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index() {
        return $this->respond($this->model->findAll());
    }
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create() {
        $json = $this->request->getJSON();
         
        $name = $json->name;
        $price = $json->price;
        $sale_price = $json->sale_price;
        $sales_count = $json->sales_count;
        $sale_date = $json->sale_date;
         
        $data = array(
            'name' => $name,
            'price' => $price,
            'sale_price' => $sale_price,
            'sales_count' => $sales_count,
            'sale_date' => $sale_date
        );
         
        $this->model->insert($data);
         
        $response = array(
            'status'   => 201,
            'messages' => array(
                'success' => 'Product created successfully'
            )
        );
         
        return $this->respondCreated($response);
    }
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function show($id = null) {
        $data = $this->model->where('id', $id)->first();
         
        if($data){
            return $this->respond($data);
        }else{
            return $this->failNotFound('No product found');
        }
    }
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function update($id = NULL){     
        $json = $this->request->getJSON();
         
        $price = $json->price;
        $sale_price = $json->sale_price;
         
        $data = array(
            'id' => $id,
            'price' => $price,
            'sale_price' => $sale_price
        );
         
        $this->model->update($id, $data);
         
        $response = array(
            'status'   => 200,
            'messages' => array(
                'success' => 'Product updated successfully'
            )
        );
       
        return $this->respond($response);
    }
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function delete($id = NULL){
        $data = $this->model->find($id);
         
        if($data) {
            $this->model->delete($id);
             
            $response = array(
                'status'   => 200,
                'messages' => array(
                    'success' => 'Product successfully deleted'
                )
            );
             
            return $this->respondDeleted($response);
        } else {
            return $this->failNotFound('No product found');
        }
    }
}
Step 7 : Create List.js File

In this step, you require to engender list.js file. So visit src/components directory and engender list.js and then integrate the following code into:

src/components
import React from 'react';
import { Link } from 'react-router-dom';
 
class Products extends React.Component {

    /*------------------------------------------
    --------------------------------------------
    constructor 
    --------------------------------------------
    --------------------------------------------*/
    constructor(props) {
        super(props);
        this.state = {products: []};
        this.headers = [
            { key: 'id', label: 'Id'},
            { key: 'name', label: 'Name' },
            { key: 'price', label: 'Price' },
            { key: 'sale_price', label: 'Selling Price' },
            { key: 'sales_count', label: 'Sales Count' },
            { key: 'sale_date', label: 'Sale Date' }
        ];
        this.deleteProduct = this.deleteProduct.bind(this);
    }
    
    /*------------------------------------------
    --------------------------------------------
    componentDidMount 
    --------------------------------------------
    --------------------------------------------*/
    componentDidMount() {
        fetch('http://localhost:8080/product')
            .then(response => {
                return response.json();
            }).then(result => {
                console.log(result);
                this.setState({
                    products:result
                });
            });
    }
    
    /*------------------------------------------
    --------------------------------------------
    delete Product 
    --------------------------------------------
    --------------------------------------------*/
    deleteProduct(id) {
        if(window.confirm("Are you sure want to delete?")) {
            fetch('http://localhost:8080/product/' + id, {
                                method : 'DELETE'
                                   }).then(response => { 
                    if(response.status === 200) {
                        alert("Product deleted successfully");
                        fetch('http://localhost:8080/product')
                        .then(response => {
                            return response.json();
                        }).then(result => {
                            console.log(result);
                            this.setState({
                                products:result
                            });
                        });
                    } 
            });
        }
    }
     
    render() {
        return (
            <div id="container">
                <Link to="/create">Add Product</Link>
                <p/>
                <table>
                    <thead>
                        <tr>
                        {
                            this.headers.map(function(h) {
                                return (
                                    <th key = {h.key}>{h.label}</th>
                                )
                            })
                        }
                          <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            this.state.products.map(function(item, key) {
                            return (
                                <tr key = {key}>
                                  <td>{item.id}</td>
                                  <td>{item.name}</td>
                                  <td>{item.price}</td>
                                  <td>{item.sale_price}</td>
                                  <td>{item.sales_count}</td>
                                  <td>{item.sale_date}</td>
                                  <td>
                                        <Link to={`/update/${item.id}`}>Edit</Link>
                                        <a href="javascript:void(0);" onClick={this.deleteProduct.bind(this, item.id)}>Delete</a>
                                  </td>
                                </tr>
                                            )
                            }.bind(this))
                        }
                    </tbody>
                </table>
            </div>
        )
    }
}
 
export default Products;
Create Update.js File src/components
import React from 'react';
import { Link, withRouter } from 'react-router-dom';

class Update extends React.Component {

    /*------------------------------------------
    --------------------------------------------
    constructor 
    --------------------------------------------
    --------------------------------------------*/
    constructor(props) {
        super(props);
        this.state = {id: '', name: '', price:'', sale_price:'', sales_count:'', sale_date:''};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    /*------------------------------------------
    --------------------------------------------
    componentDidMount 
    --------------------------------------------
    --------------------------------------------*/
    componentDidMount() {
        fetch('http://localhost:8080/product/' + this.props.match.params.id)
        .then(response => {
        return response.json();
        }).then(result => {
            console.log(result);
            this.setState({
                id:result.id,
                name:result.name,
                price:result.price,
                sale_price: result.sale_price,
                sales_count: result.sales_count,
                sale_date: result.sale_date
            });
        });
    }

    /*------------------------------------------
    --------------------------------------------
    handle Change 
    --------------------------------------------
    --------------------------------------------*/
    handleChange(event) {
        const state = this.state
        state[event.target.name] = event.target.value
        this.setState(state);
    }

    /*------------------------------------------
    --------------------------------------------
    handle Submit 
    --------------------------------------------
    --------------------------------------------*/
    handleSubmit(event) {
        event.preventDefault();
        fetch('http://localhost:8080/product/' + this.props.match.params.id, {
        method: 'PUT',
        body: JSON.stringify({
            name: this.state.name,
            price: this.state.price,
            sale_price: this.state.sale_price,
            sales_count: this.state.sales_count,
            sale_date: this.state.sale_date
        }),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
        }).then(response => {
            if(response.status === 200) {
                alert("Product update successfully.");
            }
        });
    }

    render() {
        return (
        <div id="container">
            <Link to="/">Products</Link>
            <p/>
            <form onSubmit={this.handleSubmit}>
                <input type="hidden" name="id" value={this.state.id}/>
                <p>
                    <label>Name:</label>
                    <input type="text" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Name" />
                </p>
                <p>
                    <label>Price:</label>
                    <input type="text" name="price" value={this.state.price} onChange={this.handleChange} placeholder="Price" />
                </p>
                <p>
                    <label>Selling Price:</label>
                    <input type="text" name="sale_price" value={this.state.sale_price} onChange={this.handleChange} placeholder="Selling Price" />
                </p>
                <p>
                    <label>Sales Count:</label>
                    <input type="text" name="sales_count" value={this.state.sales_count} onChange={this.handleChange} placeholder="Sales Count" />
                </p>
                <p>
                    <label>Sale Date:</label>
                    <input type="text" name="sale_date" value={this.state.sale_date} onChange={this.handleChange} placeholder="Sale Date" />
                </p>
                <p>
                    <input type="submit" value="Submit" />
                </p>
            </form>
        </div>
        );
    }
}
export default Update;
Create Style.css
#container {
    width: 800px;
    margin: auto;
}
table {
    border-collapse: collapse;
    width: 800px;
    margin: 10px auto;
}
th, td {
    border: 1px solid #ddd;
    text-align: left;
    padding: 8px;
}
tr:nth-child(even) {
    background-color: #f2f2f2
}
tr:hover {
    background-color: #ddd;
}
th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #4CAF50;
    color: white;
}
Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080

It will help you...

#Codeigniter 4