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

[5.6] Required If Rule based on a clousure or boolean value #25066

Merged
merged 8 commits into from
Aug 3, 2018
Merged

[5.6] Required If Rule based on a clousure or boolean value #25066

merged 8 commits into from
Aug 3, 2018

Conversation

alfonsobries
Copy link
Contributor

This PR will allow me to create a required rule-based in a user closure or a boolean value, the same behavior could be achieved with a custom closure but I think this provides a cleaner way to add some custom condition to require a value

Examples:

$this->validate($request->all(), [
   'role_id' => Rule::requiredIf(function () use ($request) {
   		return $request->user()->is_admin
   		   && $some_other_complicated_condition; 
    })
})
$this->validate($request->all(), [
   'role_id' => Rule::requiredIf($request->user()->is_admin)
})

@alfonsobries
Copy link
Contributor Author

alfonsobries commented Aug 2, 2018

As a quick note the main idea is to avoid this type of conditions:
'role_id' => (auth()->user()->is_admin ? 'required' : '') . '|integer'

Better:
'role_id' => [Rule::requiredIf(auth()->user()->is_admin), 'integer']

@GrahamCampbell GrahamCampbell changed the title Required If Rule based on a clousure or boolean value [5.6] Required If Rule based on a clousure or boolean value Aug 3, 2018
@taylorotwell taylorotwell merged commit 4887f9f into laravel:5.6 Aug 3, 2018
@garygreen
Copy link
Contributor

garygreen commented Aug 7, 2018

Surprised this got merged. It's just syntax sugar and yet another thing to maintain. Related to #25103

'role_id' => (auth()->user()->is_admin ? 'required' : '') . '|integer'

Better:

'role_id' => [Rule::requiredIf(auth()->user()->is_admin), 'integer']

Why is it better? Meh.

@garygreen
Copy link
Contributor

Also this opens up a whole new door of PRs. Can we also add:

requiredWithout
requiredIfNot
...

This only makes sense to me if we converted all the existing rules into first class citizens, without the need to serialize the rules to a string again. But the way Laravel works at the moment is it essentially just creates a rule-based string, so there's no real benefit from just creating that string yourself. In fact it just slows down your validation.

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