Skip to content

Commit 41c47ef

Browse files
authored
[8.x] Init the traits when the model is being unserialized (#37492)
* Init the traits when the model is being unserialized * Add tests for trait boot and initialization
1 parent f3493fc commit 41c47ef

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Illuminate/Database/Eloquent/Model.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2014,5 +2014,7 @@ public function __sleep()
20142014
public function __wakeup()
20152015
{
20162016
$this->bootIfNotBooted();
2017+
2018+
$this->initializeTraits();
20172019
}
20182020
}

tests/Integration/Queue/ModelSerializationTest.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,23 @@ public function testItReloadsNestedRelationships()
187187
$this->assertEquals($nestedUnSerialized->order->getRelations(), $order->getRelations());
188188
}
189189

190+
public function testItCanRunModelBootsAndTraitInitializations()
191+
{
192+
$model = new ModelBootTestWithTraitInitialization();
193+
194+
$this->assertTrue($model->fooBar);
195+
$this->assertTrue($model::hasGlobalScope('foo_bar'));
196+
197+
$model::clearBootedModels();
198+
199+
$this->assertFalse($model::hasGlobalScope('foo_bar'));
200+
201+
$unSerializedModel = unserialize(serialize($model));
202+
203+
$this->assertFalse($unSerializedModel->fooBar);
204+
$this->assertTrue($model::hasGlobalScope('foo_bar'));
205+
}
206+
190207
/**
191208
* Regression test for https://github.com/laravel/framework/issues/23068.
192209
*/
@@ -319,6 +336,27 @@ public function test_model_serialization_structure()
319336
}
320337
}
321338

339+
trait TraitBootsAndInitializersTest
340+
{
341+
public $fooBar = false;
342+
343+
public function initializeTraitBootsAndInitializersTest()
344+
{
345+
$this->fooBar = ! $this->fooBar;
346+
}
347+
348+
public static function bootTraitBootsAndInitializersTest()
349+
{
350+
static::addGlobalScope('foo_bar', function () {
351+
});
352+
}
353+
}
354+
355+
class ModelBootTestWithTraitInitialization extends Model
356+
{
357+
use TraitBootsAndInitializersTest;
358+
}
359+
322360
class ModelSerializationTestUser extends Model
323361
{
324362
public $table = 'users';

0 commit comments

Comments
 (0)