Skip to content

[12.x] Use pendingAttributes of relationships when creating relationship models via model factories#55558

Merged
taylorotwell merged 1 commit into
laravel:12.xfrom
gdebrauwer:factory-relationship-pending-attributes
Apr 25, 2025
Merged

[12.x] Use pendingAttributes of relationships when creating relationship models via model factories#55558
taylorotwell merged 1 commit into
laravel:12.xfrom
gdebrauwer:factory-relationship-pending-attributes

Conversation

@gdebrauwer

Copy link
Copy Markdown
Contributor

When a relationship uses the withAttributes() method, then those attributes are currently not used when creating a relationship via a parent model factory

class Page extends Model
{
    public function currentVersion(): HasOne
    {
        return $this->hasOne(PageVersion::class)->withAttributes(['is_current' => true]);
    }
}
// The created page version will not have 'is_current' set to 'true'
$page = Page::factory()->hasCurrentVersion()->create();

// You currently have to explicitly set 'is_current' to true
$page = Page::factory()->hasCurrentVersion(['is_current' => true])->create();

This PR fixes that: the relationship's pending attributes will now be used by the model factories:

// The created page version will now have 'is_current' set to 'true'
$page = Page::factory()->hasCurrentVersion()->create();

// You still can override the values of the relationship's default attributes
// I added this behavior for backward compatibility in case someone those that
$page = Page::factory()->hasCurrentVersion(['is_current' => false])->create();

@gdebrauwer gdebrauwer changed the title [12.x] Uses pendingAttributes of relationships when creating relationship models using model factories [12.x] Uses pendingAttributes of relationships when creating relationship via model factories Apr 25, 2025
@gdebrauwer gdebrauwer changed the title [12.x] Uses pendingAttributes of relationships when creating relationship via model factories [12.x] Uses pendingAttributes of relationships when creating relationship models via model factories Apr 25, 2025
@gdebrauwer gdebrauwer changed the title [12.x] Uses pendingAttributes of relationships when creating relationship models via model factories [12.x] Use pendingAttributes of relationships when creating relationship models via model factories Apr 25, 2025
@taylorotwell taylorotwell merged commit c1d8da6 into laravel:12.x Apr 25, 2025
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