jeudi 30 août 2018

Laravel SQLSTATE[23000]: Integrity constraint violation 1452

I get the following error when I try to post into the tasks table.

This is how my store function looks like:

 public function store(Request $request)
    {

        $request->validate([
            'name' => 'required|min:3|max:128',
            'status' => 'required|in:ongoing,deleted,completed',
            'dueDate' => 'required',
        ]);
        $user_id = Auth::user()->id;

        $request->request->add(['responsible_id' => $user_id]);

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

        //Task::create(request(['name', 'responsible_id', 'dueDate', 'status']));

        $tasks = Task::all();

        // And then redirect to the tasks page
        return ['data' => $tasks];
    }

My users table has the following culomns:

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

and my tasks table:

Schema::create('tasks', function (Blueprint $table) {

    $table->increments('id');
    $table->text('name');
    $table->date('dueDate');
    $table->text('status');
    $table->timestamps();

    $table->string('responsible');

    $table->integer('user_id')->unsigned();


    $table->foreign('user_id')->references('id')->on('users');

    $table->index('user_id');

});

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (homestead.tasks, CONSTRAINT tasks_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id))



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire