Replies: 2 comments
-
This is exactly what I'm looking for. What is the alternative currently ? |
Beta Was this translation helpful? Give feedback.
-
Maybe, this could even be used like |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Idea
There are a few validation rules that allow the use of the query builder, like
exists
andunique
. However, they only provide a database query builder, rather than an eloquent query builder.It would be great to be able to have the eloquent query builder to be able to make use of relationships when performing validation.
Examples
A simple example taken from the docs:
This works fine, but it feels weird if in other places of the codebase I would be doing
User::whereRelation('account', 'id', 1)
. Additionally, it's nice to be able to use the abstraction of the relationship, rather than relying on the underlying implemented foreign key column.Instead it would be great if I could do something like:
Being able to access relationships also opens the door for more complex validation, like validating belongsTo relationships.
For example, suppose I have Users, Accounts, and User Groups. I should be able to add a user to a user group that belongs to the same account as the user, but I should not be able to add a user to a user group if the user is not part of that account.
Currently, that would require a good deal of manual work to set up a validation rule for that. However, if we were to have access to the eloquent builder, this becomes very easy.
Example for adding users to user group:
Extensions
Possible ways this could be expanded further, would be to have explicit rules that help validate relationships, which could make things nice and readable:
Examples:
Considerations
In my examples I've used the
unique
andexists
rules directly for clarity, but it probably doesn't make much sense to return something different based on whether a model was passed or a table name. Instead we'd probably need to come up with different names for the rules that return an eloquent builder.Anyway, looking for feedback here. If it seems useful I can start a PR.
Beta Was this translation helpful? Give feedback.
All reactions