[11.x] Add pending attributes to child models#53677
[11.x] Add pending attributes to child models#53677tontonsb wants to merge 9 commits intolaravel:11.xfrom
Conversation
|
@tontonsb thanks for the PR. One potential inconsistency to surface... We have this method: public function withPivotValue($column, $value = null);It works very similar to this method you have proposed; however, it also sets a "where" clause on the pivot table in addition to putting the specified value on any newly created pivot models. I'm wondering if this method you're proposing should also set |
|
@taylorotwell that would make this even more convenient for my usecases. I was going to use it with a corresponding Should I also change the method to support an equivalent API? I.e. /**
* @param string|\Illuminate\Contracts\Database\Query\Expression|array<string, string> $column
* @param mixed $value
*/
public function withAttribute($column, $value = null);I'm now wondering whether I should investigate if this can be done on the Builder itself. I don't need it at the moment, but being able to not only |
|
@tontonsb yeah a similar API might be nice, in addition to |
|
@taylorotwell I added there By trying it out in an actual project, I noticed that relations created using |
|
See #53720 for a simpler implementation (without manual handling in |
|
Closing this one for now pending your other PR. |
Problem
Currently a relationship like this:
Allows you to query
$parent->children()->get()as well as create related models$parent->children()->create()that can be queried by the former$parent->children()->get().Meanwhile a scoped relationship like this:
Allows you to query for active records
$parent->children()->get(), but doing$parent->children()->create()will insert an inactive (with the default value ofactiveto be precise) child and$parent->children()->get()will not return what you just inserted.Solution
I propose adding "pending attributes" on relationships to allow specifying additional attributes that should be applied when creating new models. In theory this would allow setting any attributes on the newly created related models, but in particular this would allow solving the above issue like this:
And with such setup
$parent->children()->create()will create an activeChildModel.The pending attributes serve as defaults that can be overriden: