Skip to content

Commit

Permalink
fix newFromBuilder when model is totally guarded
Browse files Browse the repository at this point in the history
  • Loading branch information
William Feller committed May 19, 2019
1 parent dbe5468 commit 201664b
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/HasChildren.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ protected function initializeHasChildren()
if ($alias = $this->classToAlias(static::class)) {
$this->setAttribute($this->getInheritanceColumn(), $alias);
}

if (! empty($this->getGuarded())) {
$this->fillable(array_merge([$this->getInheritanceColumn()], $this->getFillable()));
}
}

public static function bootHasChildren()
Expand Down Expand Up @@ -93,7 +97,7 @@ public function newInstance($attributes = [], $exists = false)

public function newFromBuilder($attributes = [], $connection = null)
{
$model = $this->newInstance((array) $attributes, true);
$model = $this->newInstance(Arr::only((array) $attributes, $this->getInheritanceColumn()), true);

$model->setRawAttributes((array) $attributes, true);

Expand Down
10 changes: 10 additions & 0 deletions tests/Features/ParentsReturnChildrenTest.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,23 @@

use Tightenco\Parental\Tests\Models\Car;
use Tightenco\Parental\Tests\Models\Driver;
use Tightenco\Parental\Tests\Models\GuardedChild;
use Tightenco\Parental\Tests\Models\GuardedParent;
use Tightenco\Parental\Tests\Models\Passenger;
use Tightenco\Parental\Tests\Models\Plane;
use Tightenco\Parental\Tests\Models\Vehicle;
use Tightenco\Parental\Tests\TestCase;

class ParentsAreAwareOfChildrenTest extends TestCase
{
/** @test */
public function something()
{
$v = new GuardedParent;
$this->assertInstanceOf(GuardedParent::class, $v->newFromBuilder(['id' => 123]));
$this->assertInstanceOf(GuardedChild::class, $v->newFromBuilder(['id' => 123, 'type' => 'child']));
}

/** @test */
function vehicle_all_method_returns_child_models()
{
Expand Down
10 changes: 10 additions & 0 deletions tests/Models/GuardedChild.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Tightenco\Parental\Tests\Models;

use Tightenco\Parental\HasParent;

class GuardedChild extends GuardedParent
{
use HasParent;
}
15 changes: 15 additions & 0 deletions tests/Models/GuardedParent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Tightenco\Parental\Tests\Models;

use Illuminate\Database\Eloquent\Model;
use Tightenco\Parental\HasChildren;

class GuardedParent extends Model
{
use HasChildren;

protected $fillable = [];

protected $childTypes = ['child' => GuardedChild::class];
}

0 comments on commit 201664b

Please sign in to comment.