I get Laravel Error "message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list'

65 views Asked by At

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": "Illuminate\Database\QueryException", "file": "D:\laravel\Quiz-Health-Education\vendor\laravel\framework\src\Illuminate\Database\Connection.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']);
}
1

There are 1 answers

2
Lucas Pace On

Check if the created_at and updated_at columns is created. If not, create a new migration to add these columns.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

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.