[11.x] Added for
method to Eloquent models
#53610
Open
+66
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hey!
This PR proposes a new
for
method that helps set foreign keys on models. It's a fresh (and simplified!) take on my past attempt from a couple of years ago: #42467I think a major drawback of the previous approach was that it wasn't obvious whether
for
would be used in queries, or for setting fields on models. So it got a bit confusing!In this approach, I've completely ditched the Builder side of things. Although on the surface, it looks like it would have been nice, I think it would have caused more issues than it solved! So, instead, the
for
method only exists on the Model classes.So you can call it like so:
Assuming there is a
posts
andusers
relationship, the comment will now have the following data set:There's also the ability to specify the relationship name if needed:
I also quite like how it almost reads like a human-readable sentence when it's written like this too:
Hopefully this is something that other devs would also find useful. Although it's a relatively small change, I like the way that it can reduce the likelihood of typos and also uses a similar syntax to model factories.
But I completely understand if it's not something worth merging in. I'd kick myself if I didn't try and scratch the itch though haha!
If it's something you might consider merging, please let me know if there's anything you might want me to change 😄