Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Introduce Conditional trait on validation rules #37504

Merged
merged 3 commits into from
May 31, 2021

Conversation

inxilpro
Copy link
Contributor

This introduces a new Conditional trait that adds the commonly-used ->when() and ->unless() helpers. I've limited this PR to adding these helpers to validation rules, although there's an opportunity to remove some duplication on the query builder, mailables, etc., if you want to expand the scope.

I find myself using when() more and more often, and usually miss it on objects that don't have it. One classic use case is in a FormRequest object:

class PageRequest extends FormRequest
{
  public function rules()
  {
    return [
      'slug' => [
        Rule::unique(Page::class, 'slug')
          ->when($this->isMethod('put'), function($rule) {
            $rule->ignoreModel($this->route('page'));
          }),
      ],
    ];
  }
}

Something like this lets me re-use the same ruleset for create and update operations. If I'm updating an existing page, I ignore that model from the unique rule. If I'm creating a new page, there's nothing to ignore.

This can be used to add stricter options to a password rule if the logged in user has privileged access, or dynamically changing image dimension requirements based on some dynamic input.

* @param callable $callback
* @param callable|null $default
*
* @return mixed|$this
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please use the same DocBlock style as we use in the rest of the framework? Also mixed can never be combined with something else. $this is already part of mixed. Thanks

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing. I just copy-and-pasted this from the implementation in BuildsQueries, but I'll update it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although I think adding mixed|$this will provide significantly better code completion in IDEs—that's probably why it was there in the BuildsQueries DocBlock…

@taylorotwell taylorotwell merged commit 7a5d462 into laravel:8.x May 31, 2021
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.

3 participants