I have 2 table in my database.
first is table post
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->date('PostDate');
$table->string('PostTitle', 200);
$table->string('GroupID', 100)->nullable();
$table->integer('LanguageID')->default(1);
$table->timestamps();
});
second is table post_categories
Schema::create('post_categories', function (Blueprint $table) {
$table->integer('post_id');
$table->integer('category_id');
$table->timestamps();
});
Every time I store post data into database, it will stored as two rows.. because I have two active language. In my post_categories table, there has category_id column.. So, if the post data with id = 1 has 2 categories.. and the post data with id = 2 has 3 categories, it will create 5 rows in post_categories table. But when I want to delete the post, I will check from the group ID first.. So, I will delete 2 rows too.. But the problem is, I can not delete the data in post_categories.. I have using foreach but the data won't be deleted..
This is my delete Controller:
public function destroy($id)
{
$post = Post::findOrFail($id);
Post::where('GroupID', $post->GroupID)->delete();
$postGroups = Post::where('GroupID', $post->GroupID)->get();
foreach ($postGroups as $postGroup) {
DB::table('post_categories')->where('post_id', $postGroup->id)->delete();
}
return response()->json([
"error" => "0",
"message" => "Success"
]);
}
I can delete all the post with same group ID, but I can not delete the post_categories data that has same post_id.