How do I asign uncategorized category to a post after deleting it original category

  blogs, laravel, many-to-many, php, updating

Am working on a laravel blog project whereby If I delete a category, I want all posts of this category moved to ‘Uncategorized’ Category. if post belongs the deleted category and other categories also then avoid moving that post to uncategorized else move the post to uncategorized.
I am using many to many relationship for Category-Post Model. see my code below:

Post migration i have

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')
    ->constrained()
    ->onDelete('cascade');

    $table->string('title')->unique();
    $table->string('featured_image')->nullable()->default('default_featured_image.jpg');
    $table->text('detail');
    $table->string('tags')->nullable();
    $table->timestamps();
});

Category migration

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('detail',300)->nullable();
        $table->string('image')->nullable();
        $table->timestamps();
    });
}

Pivot migration for the relationship

public function up()
{
    Schema::create('category_post', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('post_id');
        $table->unsignedInteger('category_id');
        $table->timestamps();
    });
}

Post Model

 function categories(){
    return $this->belongsToMany(Category::class);
 }   

Category Model

function posts(){
   return $this->belongsToMany(Post::class);
}

Category Controller

public function destroy(Request $request)
{
   $cat_id = $request->category_id;
   $category = Category::find($cat_id);

   $posts_to_update_category_id = $category->posts()->wherePivot('category_id','=',$cat_id)->get();
   foreach($posts_to_update_category_id as $post){
       $post = Post::find($post->id);
       $post->categories()->sync(1); //uncategorized id = 1
   }
   

   $category->delete();
   return redirect('admin/category')->with('success', ''.$category->title.' has been Deleted');
}   

my problem with the code is that it end up updating all post with the deleted category id to 1(uncategorized). meaning if i have 1 post with two different categories say cat1 and cat2 and i delete cat1, i dont expect this post to be moved to uncategorized but my code does move it and also remove the cat2 from it making it just uncategorized. please help if you can. thanks

Source: Ask PHP

LEAVE A COMMENT