File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -29,7 +29,26 @@ class TermsOfUseVersion extends Model {
2929 'active ' => 'boolean ' ,
3030 ];
3131
32+ /**
33+ * Get the active ToU version.
34+ */
3235 public static function latestActiveVersion (): ?self {
33- return self ::query ()->where ('active ' , true )->latest ()->first ();
36+ return self ::query ()->where ('active ' , true )->first ();
37+ }
38+
39+ /**
40+ * Ensure only one ToU version remains active after any save operation.
41+ */
42+ protected static function booted (): void {
43+ static ::saving (function (self $ model ): void {
44+ if (!$ model ->active ) {
45+ return ;
46+ }
47+
48+ self ::query ()
49+ ->where ('version ' , '!= ' , $ model ->version )
50+ ->where ('active ' , true )
51+ ->update (['active ' => false ]);
52+ });
3453 }
3554}
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace Tests \Models ;
4+
5+ use App \TermsOfUseVersion ;
6+ use Illuminate \Foundation \Testing \RefreshDatabase ;
7+ use Tests \TestCase ;
8+
9+ class TermsOfUseVersionTest extends TestCase {
10+ use RefreshDatabase;
11+
12+ public function testSavingActiveVersionDeactivatesOtherVersions (): void {
13+ $ first = TermsOfUseVersion::create ([
14+ 'version ' => '2024-01-01 ' ,
15+ 'active ' => true ,
16+ ]);
17+
18+ $ second = TermsOfUseVersion::create ([
19+ 'version ' => '2025-01-01 ' ,
20+ 'active ' => true ,
21+ ]);
22+
23+ $ this ->assertFalse ($ first ->fresh ()->active );
24+ $ this ->assertTrue ($ second ->fresh ()->active );
25+ }
26+
27+ public function testSavingInactiveVersionDoesNotAffectExistingActiveVersion (): void {
28+ $ active = TermsOfUseVersion::create ([
29+ 'version ' => '2024-03-01 ' ,
30+ 'active ' => true ,
31+ ]);
32+
33+ TermsOfUseVersion::create ([
34+ 'version ' => '2024-04-01 ' ,
35+ 'active ' => false ,
36+ ]);
37+
38+ $ this ->assertTrue ($ active ->fresh ()->active );
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments