Skip to content

Commit 4389592

Browse files
authored
Merge pull request #358 from saernz/fix/scopes_applied_twice
Add some code to stop scopes from being applied twice.
2 parents 620d1fd + 9243333 commit 4389592

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Traits/Buildable.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,4 +292,19 @@ function () use ($arguments, $cacheKey, $method) {
292292
}
293293
);
294294
}
295+
296+
/**
297+
* Apply the scopes if they haven't already been applied, if they have
298+
* just return the builder. This prevents scopes from being applied twice.
299+
*
300+
* @return static
301+
*/
302+
public function applyScopes()
303+
{
304+
if ($this->scopesAreApplied) {
305+
return $this;
306+
}
307+
308+
return parent::applyScopes();
309+
}
295310
}

tests/Integration/CachedBuilder/ScopeTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedAuthorWithInlineGlobalScope;
99
use GeneaLabs\LaravelModelCaching\Tests\Fixtures\User;
1010
use Illuminate\Database\Eloquent\Relations\HasMany;
11+
use Illuminate\Support\Facades\DB;
1112
use Illuminate\Support\Str;
1213

1314
class ScopeTest extends IntegrationTestCase
@@ -174,4 +175,17 @@ public function testLocalScopesInRelationship()
174175
// $this->assertNotEquals($authors1, $authors2);
175176
$this->markTestSkipped();
176177
}
178+
179+
public function testScopeNotAppliedTwice()
180+
{
181+
factory(Author::class, 10)->create();
182+
$user = factory(User::class)->create(["name" => "Anton Junior"]);
183+
$this->actingAs($user);
184+
DB::enableQueryLog();
185+
$authorsA = (new AuthorBeginsWithScoped)
186+
->get();
187+
$queryLog = DB::getQueryLog();
188+
$this->assertCount(1, $queryLog);
189+
$this->assertCount(1, $queryLog[0]['bindings'], "There should only be 1 binding, scope is being applied more than once.");
190+
}
177191
}

0 commit comments

Comments
 (0)