Reputation: 845
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
, CONSTRAINTcomments_post_id_foreign
FOREIGN KEY (post_id
) REFERENCESposts
(id
)) (SQL: updateposts
setcreator_id
= 17,id
= 48)",
Upvotes: 0
Views: 7372
Reputation: 518
You can also try this.
$post = Post::where(['creator_id' => $userId, 'id' => $postid])->first();
$post->privacy = $privacy;
$post->save();
Upvotes: 3
Reputation: 145
public function changePostsPrivacy(Request $request){
$userId = $request->user()->id;
$postid = $request->get('id');
$privacy = $request->get('privacy');
$user = User::where(['id' => $userId, 'hide' => 0])->first();
if($user && $postid && in_array($privacy, [1,0])){
DB::table('posts')->update([
'privacy' => $privacy,
]);
}
creator id and id is not required to update.
Upvotes: 0
Reputation: 3869
If you have a Post model you can do :
Post::where(['creator_id' => $userId, 'id' => $postid])->update(['privacy' => $privacy]);
To prevent any foreign key error, you should use a validation request to check whether that the provided user_id
and post_id
exists.
Upvotes: 2
Reputation: 15115
u must use where condition in update privacy post
DB::table('posts')->where(['creator_id' => $userId, 'id' => $postid])->update(['privacy' => $privacy])
Upvotes: 3