mardi 29 novembre 2016

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel

I have two tables, one for users and one for the new items. I have reference for the id in the users table in the items table.

 public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('item_title');
            $table->timestamps();
        });

        Schema::table('items', function($table) {
             $table->foreign('user_id')->references('id')->on('users');
        });

This is my controller for adding new item

public function storeItem(Request $request){
        $user = Auth::user();

        $item = new Item([
            'user_id' => $user->id,
            'item_title' => $request->input('title'),
        ]);

        $item->save();    
    }

But when I submit the form I have this error SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (database.items, CONSTRAINTitems_user_id_foreignFOREIGN KEY (user_id) REFERENCESusers(id))

Any ideas?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gsfGtx
via IFTTT

Aucun commentaire:

Enregistrer un commentaire