Tutorial CRUD API Rest – CodeIgniter 4 & React.js #3 Model

CodeIgniter

Database

app/Config/Database.php

'username' => 'user',
'password' => 'password',
'database' => 'database',

Model

app/Models/CustomerModel.php

<?php namespace App\Models;

use CodeIgniter\Model;

class CustomerModel extends Model
{
   protected $table      = 'customer';
   protected $primaryKey = 'id';

   protected $returnType = 'array';
   protected $useSoftDeletes = false;

   protected $allowedFields = [
     'name',
     'email',
     'phone',
     'address'
   ];

   protected $useTimestamps = true;
   protected $createdField  = 'created_at';
   protected $updatedField  = 'updated_at';
   protected $deleted_at    = 'deleted_at';
}

SQL

--
-- Base de datos: `codeigniter`
--

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `customer`
--

CREATE TABLE `customer` (
  `id` int(11) NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_spanish2_ci NOT NULL,
  `email` varchar(100) COLLATE utf8mb4_spanish2_ci NOT NULL,
  `phone` int(11) NOT NULL,
  `address` varchar(100) COLLATE utf8mb4_spanish2_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish2_ci;

--
-- Volcado de datos para la tabla `customer`
--

INSERT INTO `customer` (`id`, `name`, `email`, `phone`, `address`, `created_at`, `updated_at`) VALUES
(1, 'Jhon Doe', '[email protected]', 31882939, 'California Cll 102', '2020-03-28 05:41:47', '2020-03-28 05:41:47'),
(15, 'Malena Morgan', '[email protected]', 31882939, 'Malibu Cll 80', '2020-03-28 06:03:46', '2020-03-28 06:03:46');

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `customer`
--
ALTER TABLE `customer`
  ADD PRIMARY KEY (`id`);

Controller

<?php namespace App\Controllers;

use CodeIgniter\Controller;
Use App\Models\CustomerModel;
 
class CustomerController extends Controller
{

	protected $customer;

	public function __construct()
	{
		 $this->customer = new CustomerModel();
	}

	public function index()
	{
		return view('customer');
	}

	public function test()
	{
		$data = $this->customer->findAll();
		return json_encode($data);
	}

}

Route

$routes->get('/api/customer/test', 'CustomerController::test');

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *