4

Hey I have problem when I insert my data from laravel to MySQL with error SQLSTATE[23000]: Integrity constraint violation: 4025 CONSTRAINT

Here is store controller

public function store(Request $request)
{
    // $faker = Faker::create('id_ID');
    $image = $request->file('Product_photo');
    $extension = $image->getClientOriginalExtension();
    $name = $request->Name;
    $file_name = $name.'.'.$extension;
    $image->move("images/listcar/", $file_name);
    DB::table('car')
    ->insert([
        //'id' => $faker->unique()->numberBetween($min = 0, $max = 200),
        'product_photo' => $file_name,
        'name' => $request->Name,
        'production_year' => $request->Production_year,
        'price' => $request->Price,
        'merk' => $request->Merk,
        'description' => $request->Description,
        'varian' => $request->Variant,
        'machine' =>$request->Machine,
        'transmision' => $request->Transmision,
        'wheel' => $request->Wheel,
    ]);
    return redirect('/admin');

Here is my blade

<body>
<h1>Tambah Mobil</h1>
<div class="container">
    <form action="/car/add" method="post" enctype="multipart/form-data">
    {{ csrf_field() }}
    <th>Nama</th><br>
        <input type="text" name="Name" value=""><br/><br>
    <th>Tahun Produksi</th><br>
        <input type="text" name="Production_year" value=""><br/><br>
    <th>Harga</th><br>
        <input type="number" name="Price" value=""><br/><br>
    <th>Select Product Image</th><br>
        <input type="file" name="Product_photo" /><br/><br>
    <th>Merek</th><br>
        <input type="text" name="Merk" value=""><br/><br>
    <th>Deskripsi</th><br>
        <input type="textarea" name="Description" value=""><br/><br>
    <th>Varian</th><br>
        <input type="text" name="Variant" value=""><br/><br>
    <th>Mesin</th><br>
        <input type="text" name="Machine" value=""><br/><br>
    <th>Transmisi</th><br>
        <input type="text" name="Transmision" value=""><br/><br>
    <th>Penggerak Roda</th><br>
        <input type="text" name="Wheel" value=""><br/><br>
    <br>
        <input class="btn btn-primary" type="submit" value="Tambah Data Mobil">
    </form>
    <br>
    <br>
</div>

MySQL structure enter image description here

I really dont know where I went wrong, so please tell me if there is a wrong concepts

5
  • 1
    You don't set the primary key manually, the database will assign it when the record is inserted. Remove this 'id' => $faker->unique()->numberBetween($min = 0, $max = 200),
    – Brian Lee
    Nov 26, 2020 at 3:52
  • @vandettadyckies You need to set id as auto increment and then no need of setting it through Faker. Nov 26, 2020 at 4:12
  • 2
    Reporting about error provide complete error message, do not strip it.
    – Akina
    Nov 26, 2020 at 5:06
  • okaiy, i allready update it, now i'm using auto increment, but same error still happening Nov 26, 2020 at 6:23
  • Try clearing the table and start from scratch since your column "id" are messed up. It will be all god now since you added auto increment property Nov 26, 2020 at 6:55

6 Answers 6

9

Change collation on mysql table - utf8mb4_general_ci : )

3
  • 2
    This is one of the good answer
    – Shapon Pal
    Mar 15, 2022 at 8:36
  • 2
    Brief and useful Feb 15 at 14:54
  • This was super helpful! Mine was set to utf8mb4_bin no idea why Mar 17 at 18:06
3

i had same problem and solved:

if you save non-json into JSON field this error occurred like this:

    $item = new WhatsAppWebhook($data);
    $item->save();
    return $item;

you need to encode

    $payload = array("payload"=>json_encode($data));
    $item = new WhatsAppWebhook($payload);
    $item->save();
    return $item;
1
  • Better solution. I suspected this when i got the error. Turns out it was a code mistake Nov 13 at 22:46
0

Check you model $fillable array. Ensure all columns that records will be inserted are part of your $fillable

0
$user_role = array(('role')=>json_encode($request['role']));
$user_role = implode(', ', $user_role);
1
  • 1
    This answer was reviewed in the Low Quality Queue. Here are some guidelines for How do I write a good answer?. Code only answers are not considered good answers, and are likely to be downvoted and/or deleted because they are less useful to a community of learners. It's only obvious to you. Explain what it does, and how it's different / better than existing answers. From Review Aug 26, 2022 at 22:52
0

I recently encountered a Laravel 'constraint violation' error related to JSON field. The logs were not revealing and the bug was intermittent. It took me some time, but fortunately the fix was easy.

TL;DR

  • Problem: In Laravel's Model class I had set the field to guarded and then provided an invalid default value.
  • Solution: In Laravel make the default values of your model's JSON fields valid JSON encoded strings. Even when they are empty {}.

The Error

When I deployed code to the production environment for the first time, I saw a HTTP-500 error which had not arisen in my local testing:

[2022-09-27 03:54:27] local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 
4025 CONSTRAINT `table.field3` failed for `database`.`table` (SQL: insert into `table` (`field1`, `field2`, `field3`
...
#0 /path/to/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php(719): 
Illuminate\\Database\\Connection->runQueryCallback('insert into `ta...', Array, Object(Closure))

Not a very illuminating (pun intended) log entry, plus I could not reproduce the error in my vagrant development environment. The only difference between the vagrant box and production was that MariaDB was version 10.9 versus version 10.7 in production.

The Problem

It turns out the field type being json() in the Laravel migration was significant.

database/migrations/2022_09_25_133630_create_model_table.php :

new class extends Migration
{
    public function up()
    {
        Schema::create('my_model', function (Blueprint $table) {
            $table->id();
            ...
            $table->json('field3');

I had always wondered why Laravel bothered with so many field types in the migration when they all got reduced to a handful once the SQL tables were created. In this instance the MariaDB column was longtext (non-nullable).

In Laravel's Model class I had set the field to guarded and then provided a default value which I thought was appropriate.

app/Models/my_model.php :

class my_model extends Model
{
    use HasFactory;

    /**
     * The attributes that are NOT mass assignable.
     *
     * @var string[]
     */
    protected $guarded = [
        'field3'
    ];

    /**
     * Default values for attributes.
     *
     * @var array
     */
    protected $attributes = [
        'field3' => "",
    ];

It must be that the underlying mechanism of how the field was stored across the two versions of MariaDB came to the fore here? The error had arisen because an empty string which I had provided as a default value is not a valid JSON encoding and thus not compatible with the Laravel field type of json(). In my defense it is perfectly valid in the context of a non-nullable longtext column in MariaDB.

The Solution

In Laravel make the default values of your model's JSON fields valid JSON encoded strings.

app/Models/my_model.php :

class my_model extends Model
{
    use HasFactory;

    /**
     * The attributes that are NOT mass assignable.
     *
     * @var string[]
     */
    protected $guarded = [
        'field3'
    ];

    /**
     * Default values for attributes.
     *
     * @var array
     */
    protected $attributes = [
        'field3' => "{}",
    ];
0

This error may also occur in case a field that is not nullable and has no default value is left without value.

To fix this either add default values in your code or in your migraitons.

Here is a migration sample that updates email field to nullable and sets price default value to zero:

<?php

Schema::table('users', function (Blueprint $table) {
    $table->string('email', 255)->nullable()->change();
    $table->integer('price')->default(0)->change();
});

https://laravel.com/docs/8.x/migrations#column-modifiers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.