Skip to content

Conversation

@AndrewMast
Copy link
Contributor

Why

The withAttributes method (documented here) is very helpful for adding attributes to both the where clauses as well as the attributes when a model is made from the relationship.

However, I ran into a situation where I needed to set an attribute when the relationship is created, but not constrain the relationship to only rows where the attribute is set to that value.

The $pendingAttributes property already exists on the Eloquent builder and all the logic to add the pending attributes to the new models also exist.

What

This led to me creating the pendingAttributes method to do the same thing as withAttributes but not touch the where clauses.

Implementation:

/**
 * Specify attributes that should be added to any new models created by this builder.
 *
 * @param  \Illuminate\Contracts\Database\Query\Expression|array|string  $attributes
 * @param  mixed  $value
 * @return $this
 */
public function pendingAttributes(Expression|array|string $attributes, $value = null)
{
    if (! is_array($attributes)) {
        $attributes = [$attributes => $value];
    }

    $this->pendingAttributes = array_merge($this->pendingAttributes, $attributes);

    return $this;
}

Tests:

  • tests/Database/DatabaseEloquentBelongsToManyPendingAttributesTest.php
    Copied from DatabaseEloquentBelongsToManyWithAttributesTest.php and made sure only the relational where clauses exist
  • tests/Database/DatabaseEloquentHasOneOrManyPendingAttributesTest.php
    Copied from DatabaseEloquentHasOneOrManyWithAttributesTest.php and made sure only the relational where clauses exist
  • tests/Database/DatabaseEloquentPendingAttributesTest.php
    Copied from DatabaseEloquentWithAttributesTest.php and made sure no where clauses

@taylorotwell
Copy link
Member

I would rather have a flag on withAttributes that users can pass via a named argument.

@AndrewMast AndrewMast deleted the feat/builder-pending-attributes branch March 28, 2025 19:16
@AndrewMast AndrewMast restored the feat/builder-pending-attributes branch March 28, 2025 19:20
@AndrewMast
Copy link
Contributor Author

I reattempted this using a named argument in PR #55199.

@AndrewMast AndrewMast deleted the feat/builder-pending-attributes branch March 29, 2025 17:32
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