Search code examples
phpcodeignitercodeigniter-4

Unable to insert data in CodeIgniter 4


I am trying out CodeIgniter 4 and I have a problem inserting data.

In my model I only defined the table name, no methods, no nothing. I can display all data in my table but when it comes to inserting data something goes wrong.

My controller code looks like:

$data = [
            'sum' => '23',
            'type' => 'in',
            'name' => 'asd'
        ];


        $expense = new ExpensesModel();

        try {
            var_dump($expense->insert($data));

        } catch (\ReflectionException $e) {
            var_dump($e);
        }

When I call this endpoint using Postman I get a 500 internal server error. If I die('asd') before the try-catch I can see the message so this makes me think something happens during the insert method call.

How can I debug this ?


Solution

  • If all you defined within the model was the table name, then you never defined $allowedFields (https://codeigniter.com/user_guide/models/model.html):

    This array should be updated with the field names that can be set during save, insert, or update methods.

    You should probably read through that documentation. Moreover, you would troubleshoot these issues by looking at the logs within your project's writable/logs directory, although in this case CI would not consider this a failure as it was you not defining what's allowed into the DB.