I'm trying to do a CRUD with Codeigniter 4, it's my first time using this framework. I created the Database in Mysql and I have already done the register and login ( they work at the moment) So on the landing page, I created a button to edit the user data. But it doesn't work.... only shows me the last error which means that the save function isn't working properly. Someone can help me? I'm super lost at this moment!
This is my edit controller
<?php
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;
class Edit extends BaseController
{
public function index()
{
if (!$this->session->has('user_id')) {
return redirect()->to('/login');
}
$user = session()->get('user_data');
if ($user === null) {
return redirect()->to('/landing')->with('error', 'No se pudieron obtener los datos del usuario.');
}
return view('edit', ['user' => $user]);
}
public function save()
{
if (!$this->session->has('user_id')) {
return redirect()->to('/login');
}
if ($this->request->getMethod() === 'post') {
$userData = [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email'),
// Puedes agregar el campo password si es necesario, pero ten en cuenta que no es seguro almacenar contraseñas en texto plano.
// 'password' => $this->request->getPost('password'),
];
if (empty($userData['name']) || empty($userData['email'])) {
return redirect()->to('/edit')->with('error', 'Por favor, complete todos los campos.');
}
$userModel = new UserModel();
$updateStatus = $userModel->update(session()->get('user_id'), $userData);
echo $userData;
if ($updateStatus) {
session()->set('user_data', $userData);
return redirect()->to('/edit')->with('success', 'Perfil actualizado con éxito');
} else {
return redirect()->to('/home')->with('error', 'No se pudo actualizar el perfil.');
}
}
return redirect()->to('/edit')->with('error', 'Método de solicitud no permitido.');
}
}
This is my view
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Editar Perfil</title>
<link href="<?= base_url('node_modules/bootstrap/dist/css/bootstrap.min.css') ?>" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1 class="text-center">Editar Perfil</h1>
<!-- Mensajes de éxito o error -->
<?php if (session()->getFlashdata('success')) : ?>
<div class="alert alert-success" role="alert">
<?= session()->getFlashdata('success') ?>
</div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')) : ?>
<div class="alert alert-danger" role="alert">
<?= session()->getFlashdata('error') ?>
</div>
<?php endif; ?>
<?php if (isset($user) && $user !== null) : ?>
<form action="<?= base_url('edit-users') ?>" method="post">
<div class="mb-3">
<label for="name" class="form-label">Nombre</label>
<input type="text" class="form-control" id="name" name="name" value="<?= esc($user['name']) ?>" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Correo Electrónico</label>
<input type="email" class="form-control" id="email" name="email" value="<?= esc($user['email']) ?>" required>
</div>
<!-- Si necesitas manejar contraseñas, añade el campo de contraseña, pero ten en cuenta la seguridad -->
<!-- <div class="mb-3">
<label for="password" class="form-label">Contraseña</label>
<input type="password" class="form-control" id="password" name="password">
</div> -->
<button type="submit" class="btn btn-primary">Guardar Cambios</button>
</form>
<?php else : ?>
<div class="alert alert-danger" role="alert">
No se pudieron cargar los datos del usuario.
</div>
<?php endif; ?>
<a href="<?= base_url('landing') ?>" class="btn btn-secondary mt-3">Cancelar</a>
</div>
<script src="<?= base_url('node_modules/bootstrap/dist/js/bootstrap.bundle.min.js') ?>"></script>
</body>
</html>
And this is my model that works with the register
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'user';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email', 'password'];
protected $beforeInsert = ['hashPassword'];
protected $beforeUpdate = ['hashPassword'];
protected function hashPassword(array $data)
{
if (isset($data['data']['password'])) {
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
}
return $data;
}
/**
* Método para obtener un usuario por su correo electrónico.
*
* @param string $email
* @return array|null
*/
public function getUserByEmail($email)
{
return $this->where('email', $email)->first();
}
/**
* Método para guardar un nuevo usuario en la base de datos.
*
* @param array $data
* @return int|false ID del usuario insertado o false si falla
*/
public function saveUser($data)
{
try {
return $this->insert($data);
} catch (\Exception $e) {
if ($this->db->error()['code'] == 1062) {
return false;
} else {
throw $e;
}
}
}
public function updateUser($id, $data)
{
return $this->where('id', $id)->set($data)->update();
}
}
And my routes
$routes->get('/', 'Home::index');
$routes->get('/register', 'Register::index');
$routes->post('/register-users', 'Register::save');
$routes->get('/login', 'Login::index');
$routes->post('/login-users', 'Login::process');
$routes->get('/edit', 'Edit::index');
$routes->post('/edit-users', 'Edit::save');
$routes->get('/landing', 'Landing::index');
$routes->post('/logout', 'Landing::logout');
It's difficult to catch the error with tthe console in php
if (isset($user) && $user !== null)doesn't make sense if you know whatisset()does.