Skip to content

Commit

Permalink
[8.x] Init the traits when the model is being unserialized (laravel#3…
Browse files Browse the repository at this point in the history
…7492)

* Init the traits when the model is being unserialized

* Add tests for trait boot and initialization
  • Loading branch information
mtawil authored May 27, 2021
1 parent f3493fc commit 41c47ef
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -2014,5 +2014,7 @@ public function __sleep()
public function __wakeup()
{
$this->bootIfNotBooted();

$this->initializeTraits();
}
}
38 changes: 38 additions & 0 deletions tests/Integration/Queue/ModelSerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,23 @@ public function testItReloadsNestedRelationships()
$this->assertEquals($nestedUnSerialized->order->getRelations(), $order->getRelations());
}

public function testItCanRunModelBootsAndTraitInitializations()
{
$model = new ModelBootTestWithTraitInitialization();

$this->assertTrue($model->fooBar);
$this->assertTrue($model::hasGlobalScope('foo_bar'));

$model::clearBootedModels();

$this->assertFalse($model::hasGlobalScope('foo_bar'));

$unSerializedModel = unserialize(serialize($model));

$this->assertFalse($unSerializedModel->fooBar);
$this->assertTrue($model::hasGlobalScope('foo_bar'));
}

/**
* Regression test for https://github.com/laravel/framework/issues/23068.
*/
Expand Down Expand Up @@ -319,6 +336,27 @@ public function test_model_serialization_structure()
}
}

trait TraitBootsAndInitializersTest
{
public $fooBar = false;

public function initializeTraitBootsAndInitializersTest()
{
$this->fooBar = ! $this->fooBar;
}

public static function bootTraitBootsAndInitializersTest()
{
static::addGlobalScope('foo_bar', function () {
});
}
}

class ModelBootTestWithTraitInitialization extends Model
{
use TraitBootsAndInitializersTest;
}

class ModelSerializationTestUser extends Model
{
public $table = 'users';
Expand Down

0 comments on commit 41c47ef

Please sign in to comment.