'"SQLSTATE[23000]: Integrity constraint violation: 1048 Column laravel
I am trying to post some data just to test the api if it working or not. Fortunately it's not working. project is connected with the database . It's working fine when I fetch the data but not working when I post the data.
"message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into employees (name, address, updated_at, created_at) values (?, ?, 2022-01-24 17:49:27, 2022-01-24 17:49:27))",
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('address');
$table->timestamps();
});
}
public function store(Request $req)
{
//
$employee = new Employee;
$employee->name = $req->name;
$employee->address=$req->address;
$employee->save();
}
Route::apiResource('/employee', App\Http\Controllers\EmployeeController::class);
Solution 1:[1]
As you can see in the error message - your columns are not passed to the sql statement. The placeholder in your SQL statement for name and address are empty, but those columns need to have data cause they are not defined as nullable.
SQL: insert into employees (name, address, updated_at, created_at) values (?, ?, 2022-01-24 17:49:27, 2022-01-24 17:49:27)
Only updated_at and created_at hold timestamps inserted by laravel.
You have to pull the data from the request object with $req->all() or by using the column names and input mehtod like $name = $req->input('name')
See: https://laravel.com/docs/8.x/requests#accessing-the-request
Solution 2:[2]
The name and address values are null, as you can see from your error message there are two question marks for those columns.
employees (name, address, updated_at, created_at) values (?, ?, 2022-01-24 17:49:27, 2022-01-24 17:49:27))
You can access request properties like that so it is likely to be your code for sending the request isn't inserting the name and address properties before sending.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | C4pt4inC4nn4bis |
| Solution 2 | Josh Bonnick |
