Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 inserting row with a foreign key

I have two tables Users and Posts. here is my User table migration file:

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

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users');
}

and here is my posts table migration file

public function up()
{
    Schema::create('posts', function(Blueprint $table){

        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->integer('user_id')->unsigned();
        $table->string('slug');
        $table->timestamps();


    });

    Schema::table('posts',function(Blueprint $table){

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

    });
}

AdminPostsController extends Controller{ public function store(Request $request) {

    $validator = Validator::make($request->all(),Post::$rules);


    if($validator->passes()){



        $post = new Post();

        $post->title = $request->get('title');
        $post->body = $request->get('body');
        $post->user_id = $request->get('id');
        $post->slug = Slug::generateSlug($request->get('title'));

        $post->save();

        return Redirect::route('admin.posts.index');
    }
    else{
            return Redirect::route('admin.posts.create')->withErrors($validator)->withInput();
    }

}

}

Every time i insert a new post,i always see the following error

"QueryException in Connection.php line 614: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ('blog'.'posts', CONSTRAINT 'posts_user_id_foreign' FOREIGN KEY ('user_id') REFERENCES 'users' ('id') ON DELETE CASCADE ON UPDATE CASCADE)"

i would like to know what i am doing wrong.

like image 943
Gaetan Sobze Avatar asked Mar 04 '15 15:03

Gaetan Sobze


1 Answers

This code creates a constrain so that your post MUST be referenced by a valid user id. The user_id field must contain a existing key on the users table id field.

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

Try associating the user before saving the new post.

$post        = new Post();
$post->title = $request->get('title');
$post->body  = $request->get('body');

$post->user()->associate($user);
$post->save();

Assuming that you have a valid user model loaded on the $user var and that you have set the relationship between Users and Posts on the Models.

like image 148
Arthur Samarcos Avatar answered Nov 11 '22 00:11

Arthur Samarcos