Search code examples
databaselaravelphpmyadminpostmandatabase-migration

update column value in laravel 5.4


i want to update privacy of a post

my controller

   public function changePostsPrivacy(Request $request){
            $userId = $request->user()->id;
            $postid = $request->get('id');
            //dd($postid);
            $privacy = $request->get('privacy');//dd($privacy);
            $user = User::where(['id' => $userId, 'hide' => 0])->first();
            if($user && $postid && in_array($privacy, [1,0])){
                DB::table('posts')->update(['creator_id' => $userId, 'id' => $postid],[
                    'privacy' => $privacy,
                ]);
            }
        }

Route :

 Route::group(['middleware'=>['auth:api', \App\Http\Middleware\OnlyRegisteredUsers::class]], function(){
        /**
         * Group for registered users only APIs
         */
        Route::post('changePostsPrivacy','UserController@changePostsPrivacy');
    });

Migration

 public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->longText('content');
            $table->string('short_description');
            $table->unsignedInteger('media_id')->nullable();
            $table->foreign('media_id')->references('id')->on('medias');
            $table->unsignedInteger('creator_id');
            $table->foreign('creator_id')->references('id')->on('users');
            $table->boolean('hide')->default(0);
            $table->timestamps();
        });
    }

new column added in this this migration

 public function up()
        {
            Schema::table('posts', function (Blueprint $table) {
                $table->integer('privacy')->after('creator_id');
            });
        }

when i want to add privacy to any post it gives me an error

"message": "SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (webdb.comments, CONSTRAINT comments_post_id_foreign FOREIGN KEY (post_id) REFERENCES posts (id)) (SQL: update posts set creator_id = 17, id = 48)",


Solution

  • u must use where condition in update privacy post

    DB::table('posts')->where(['creator_id' => $userId, 'id' => $postid])->update(['privacy' => $privacy])