Codeigniter 4 – Updating and Deleting using model with Example
Updating Data
- Use the update() method to update existing data.
Example:
namespace App\Models;
use CodeIgniter\Model;
class User extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
public function updateUser($id, $data)
{
return $this->update($id, $data);
}
}
Updating Data with Conditions
- Use the update() method with conditions to update specific data.
Example:
public function updateUser($name, $data)
{
return $this->where('name', $name)->update($data);
}
Deleting Data
- Use the delete() method to delete existing data.
Example:
public function deleteUser($id)
{
return $this->delete($id);
}
Deleting Data with Conditions
- Use the delete() method with conditions to delete specific data.
Example:
public function deleteUser($name)
{
return $this->where('name', $name)->delete();
}
Soft Deleting Data
- Use the purgeDeleted() method to soft delete data.
Example:
public function softDeleteUser($id)
{
return $this->purgeDeleted($id);
}
Restoring Soft Deleted Data
- Use the restoreDeleted() method to restore soft deleted data.
Example:
public function restoreUser($id)
{
return $this->restoreDeleted($id);
}
I hope this helps! Let me know if you have any further questions or need more information.
Note: Updating and deleting data using a Model in CodeIgniter 4 provides a simple and intuitive way to interact with the database. It helps to keep the code organized and maintainable.