skip to Main Content

I make a controller function to insert new records on the quizzes table. To do that, I used Laravel mass assignment, and after that, I got this error message.

"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column
‘updated_at’ in ‘field list’ (Connection: mysql, SQL: insert into
quizzes (title, isfree, updated_at, created_at) values
(Menjaga Pola Makan, 1, 2024-01-13 06:20:07, 2024-01-13 06:20:07))",
"exception": "IlluminateDatabaseQueryException",
"file": "D:laravelQuiz-Health-EducationvendorlaravelframeworksrcIlluminateDatabaseConnection.php",
"line": 822

Controller

public function create(Request $request)
{
    $request->validate([
        'title'=>'required',
        'isfree'=>'required|boolean',
        'img'=>'string|nullable',
        'price'=>'nullable',
        'disc'=>'nullable'
    ]);

    if($request->isfree === false)
    {
        $request['price'] = null;
        $request['disc'] = null;
    }

    $request['created_at'] = $request->date('d-m-Y');

    Quiz::create($request->all());

    return response()->json(['status' => 'success']);
}

2

Answers


  1. The error message indicates that Laravel is trying to update the updated_at column in your quizzes table, but it can’t find the column. Laravel expects created_at and updated_at columns to exist in your tables. If your quizzes table does not have an updated_at column and you do not want to add one, you can disable the timestamp feature in your Quiz model.

    class Quiz extends Model
    {
        public $timestamps = false;
    
        // ...
    }
    
    Login or Signup to reply.
  2. Check if the created_at and updated_at columns is created. If not, create a new migration to add these columns.

    <?php
    
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateSupportFacadesSchema;
    
    return new class extends Migration {
        public function up()
        {
            Schema::create('quizzes', function (Blueprint $table) {
                $table->timestamps();
            });
        }
    };
    

    Additionally, you are manually defining the created_at value. It’s not a good practice.
    The column will automatically generate the value when Quiz is created (using the date and time of creation moment).

    If there is a user-inserted value that needs to be stored, it is advisable to create a dedicated column for that input.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search