Skip to content

Commit

Permalink
Allow mass assigmnet with mutators when using guard
Browse files Browse the repository at this point in the history
  • Loading branch information
Apfelfrisch committed Sep 28, 2024
1 parent 0d78422 commit e345471
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,10 @@ public function isGuarded($key)
*/
protected function isGuardableColumn($key)
{
if ($this->hasSetMutator($key) || $this->hasAttributeSetMutator($key)) {
return true;
}

if (! isset(static::$guardableColumns[get_class($this)])) {
$columns = $this->getConnection()
->getSchemaBuilder()
Expand All @@ -222,6 +226,7 @@ protected function isGuardableColumn($key)
if (empty($columns)) {
return true;
}

static::$guardableColumns[get_class($this)] = $columns;
}

Expand Down
58 changes: 58 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3143,6 +3143,32 @@ public function testModelToJsonSucceedsWithPriorErrors(): void

$this->assertSame('{"name":"Mateus"}', $user->toJson(JSON_THROW_ON_ERROR));
}

public function testFillableWithMutators()
{
$model = new EloquentModelWithMutators;
$model->fillable(['full_name', 'full_address']);
$model->fill(['id' => 1, 'full_name' => 'John Doe', 'full_address' => '123 Main Street, Anytown']);

$this->assertNull($model->id);
$this->assertSame('John', $model->first_name);
$this->assertSame('Doe', $model->last_name);
$this->assertSame('123 Main Street', $model->address_line_one);
$this->assertSame('Anytown', $model->address_line_two);
}

public function testGuardedWithMutators()
{
$model = new EloquentModelWithMutators;
$model->guard(['id']);
$model->fill(['id' => 1, 'full_name' => 'John Doe', 'full_address' => '123 Main Street, Anytown']);

$this->assertNull($model->id);
$this->assertSame('John', $model->first_name);
$this->assertSame('Doe', $model->last_name);
$this->assertSame('123 Main Street', $model->address_line_one);
$this->assertSame('Anytown', $model->address_line_two);
}
}

class EloquentTestObserverStub
Expand Down Expand Up @@ -3870,3 +3896,35 @@ protected function stepOut(): void
}
}
}

class EloquentModelWithMutators extends Model
{
public $attributes = [
'first_name' => null,
'last_name' => null,
'address_line_one' => null,
'address_line_two' => null,
];

protected function fullName(): Attribute
{
return Attribute::make(
set: function (string $fullName) {
[$firstName, $lastName] = explode(' ', $fullName);

return [
'first_name' => $firstName,
'last_name' => $lastName,
];
}
);
}

public function setFullAddressAttribute($fullAddress)
{
[$addressLineOne, $addressLineTwo] = explode(', ', $fullAddress);

$this->attributes['address_line_one'] = $addressLineOne;
$this->attributes['address_line_two'] = $addressLineTwo;
}
}

0 comments on commit e345471

Please sign in to comment.