diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index b6982c42ed14..2078e4db0a59 100755 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -2266,9 +2266,11 @@ public static function unguarded(callable $callback) static::unguard(); - $result = $callback(); - - static::reguard(); + try { + $result = $callback(); + } finally { + static::reguard(); + } return $result; } diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 3a81f710369b..1e2d71b4a4cf 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -794,6 +794,18 @@ public function testUnguardedCallDoesNotChangeUnguardedState() Model::reguard(); } + public function testUnguardedCallDoesNotChangeUnguardedStateOnException() + { + try { + Model::unguarded(function () { + throw new Exception; + }); + } catch (Exception $e) { + // ignore the exception + } + $this->assertFalse(Model::isUnguarded()); + } + public function testHasOneCreatesProperRelation() { $model = new EloquentModelStub;