Skip to content

Commit b5ed5ba

Browse files
daunryanmitchell
andauthored
Prevent creation of duplicate terms on slug change (#384)
* Fetch term by old slug if present Signed-off-by: Philipp Daun <[email protected]> * Add a test --------- Signed-off-by: Philipp Daun <[email protected]> Co-authored-by: Ryan Mitchell <[email protected]>
1 parent 9b69409 commit b5ed5ba

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/Taxonomies/Term.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,11 @@ public static function makeModelFromContract(Contract $source)
7474
}
7575

7676
return $class::firstOrNew([
77-
'slug' => $source->slug(),
77+
'slug' => $source->getOriginal('slug', $source->slug()),
7878
'taxonomy' => $source->taxonomy(),
7979
'site' => $source->locale(),
8080
])->fill([
81+
'slug' => $source->slug(),
8182
'uri' => $source->uri(),
8283
'data' => $data,
8384
'updated_at' => $source->lastModified(),

tests/Terms/TermTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
namespace Tests\Terms;
4+
5+
use Illuminate\Foundation\Testing\RefreshDatabase;
6+
use PHPUnit\Framework\Attributes\Test;
7+
use Statamic\Eloquent\Taxonomies\Taxonomy;
8+
use Statamic\Eloquent\Taxonomies\TermModel;
9+
use Statamic\Facades\Term as TermFacade;
10+
use Tests\TestCase;
11+
12+
class TermTest extends TestCase
13+
{
14+
use RefreshDatabase;
15+
16+
#[Test]
17+
public function it_doesnt_create_a_new_model_when_slug_is_changed()
18+
{
19+
Taxonomy::make('test')->title('test')->save();
20+
21+
$term = tap(TermFacade::make('test-term')->taxonomy('test')->data([]))->save();
22+
23+
$this->assertCount(1, TermModel::all());
24+
$this->assertSame('test-term', TermModel::first()->slug);
25+
26+
$term->slug('new-slug');
27+
$term->save();
28+
29+
$this->assertCount(1, TermModel::all());
30+
$this->assertSame('new-slug', TermModel::first()->slug);
31+
}
32+
}

0 commit comments

Comments
 (0)