fix(products): keep category when update sends null product_categories_id

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-21 16:59:15 +07:00
co-authored by Claude Sonnet 5.5
parent a443ec3bf6
commit 4f3442190e
2 changed files with 39 additions and 0 deletions
@@ -173,6 +173,10 @@ class ProductController extends Controller
'features' => 'nullable|array',
]);
if (array_key_exists('product_categories_id', $validated) && $validated['product_categories_id'] === null) {
unset($validated['product_categories_id']);
}
if (isset($validated['name']) && $validated['name'] !== $product->name) {
$validated['slug'] = Str::slug($validated['name']);
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Admin\Product;
use App\Models\Product;
use App\Models\ProductCategories;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class ProductUpdateCategoryTest extends TestCase
{
use RefreshDatabase;
public function test_null_category_keeps_existing_category(): void
{
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
$admin = User::factory()->create();
$admin->assignRole('Full Administrator');
$category = ProductCategories::create(['name' => 'VPS', 'slug' => 'vps', 'is_active' => true, 'sort_order' => 1]);
$product = Product::factory()->create(['product_categories_id' => $category->id]);
$this->actingAs($admin, 'admin')
->putJson("/api/v1/administrator/products/{$product->id}", [
'name' => 'Renamed',
'product_categories_id' => null,
])
->assertOk();
$this->assertSame($category->id, $product->fresh()->product_categories_id);
}
}