Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow mass assignment with mutators when using model::guarded #52962

Merged

Conversation

Apfelfrisch
Copy link
Contributor

@Apfelfrisch Apfelfrisch commented Sep 27, 2024

When using mass assignment to populate model attributes, mutators are ignored if the mutator attribute doesn't mirror the table column and model::guarded is filled.

Example from the Laravel Documentation:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
     protected $guarded = []; // works
     protected $fillable = ['address']; // works
     protected $guarded  = ['some_unrelated_column']; // doesn't work
    
    /**
     * Interact with the user's address.
     */
    protected function address(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => new Address(
                $attributes['address_line_one'],
                $attributes['address_line_two'],
            ),
            set: fn (Address $value) => [
                'address_line_one' => $value->lineOne,
                'address_line_two' => $value->lineTwo,
            ],
        );
    }
}

$user = new User;
$user->fill(['address' => new Address(...)]);

I modified two tests to demonstrate the issue:

  • Test DatabaseEloquentModelTest::testFillable already passes without this PR.
  • Test DatabaseEloquentModelTest::testGuarded fails, illustrating the problem.

@Apfelfrisch Apfelfrisch changed the title fix: Allow mass assignment with mutators when using model::guarded Allow mass assignment with mutators when using model::guarded Sep 27, 2024
@taylorotwell
Copy link
Member

Is it possible to make this change without modifying any existing tests at all?

@taylorotwell taylorotwell marked this pull request as draft September 27, 2024 15:11
@Apfelfrisch Apfelfrisch force-pushed the attribute-casting-with-guard branch 2 times, most recently from 31ad945 to 2a5bd25 Compare September 27, 2024 18:11
@Apfelfrisch Apfelfrisch force-pushed the attribute-casting-with-guard branch from 2a5bd25 to e345471 Compare September 28, 2024 06:04
@Apfelfrisch
Copy link
Contributor Author

Apfelfrisch commented Sep 28, 2024

Sure.

I added a new Stub EloquentModelWithMutators and two test methods: testFillableWithMutators and testGuardedWithMutators.

EloquentModelWithMutators
This stub was needed because we didn't have one that mutates via Attribute.

testFillableWithMutators
This test already passes without the PR. We can leave it out if you think it’s not necessary.

testGuardedWithMutators
This one fails with Error: Call to a member function connection() on null without the PR, because it tries to look up full_name and full_address. If we mock the DB columns like so

class DatabaseEloquentModelTest extends TestCase
{
    //...

    public function testGuardedWithMutators()
    {
        // Mocking the DB columns
        EloquentModelStub::setConnectionResolver($resolver = m::mock(Resolver::class));
        $resolver->shouldReceive('connection')->andReturn($connection = m::mock(stdClass::class));
        $connection->shouldReceive('getSchemaBuilder->getColumnListing')->andReturn([
            'id', 'first_name', 'last_name', 'address_line_one', 'address_line_two',
        ]);

        $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 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;
    }
}

we get a more meaningful assertion: Failed asserting that null is identical to 'John'. But since the lookup is avoided, I left it out.

@Apfelfrisch Apfelfrisch marked this pull request as ready for review October 1, 2024 07:20
@taylorotwell taylorotwell merged commit 045bc79 into laravel:11.x Oct 1, 2024
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants