0

I'm using the dwightwatson/validating package to create validation rules in the model.

I particularly like the custom rulesets you can create for different routes.

Model

protected $rulesets = [
        'set_up_all' => [
            'headline' => 'required|max:100',
            'description' => 'required'
        ],
        'set_up_property' => [
            'pets' => 'required'
        ],
        'set_up_room' => [
            'residents_gender' => 'required',
            'residents_smoker' => 'required'
        ],
        'set_up_roommate' => [
            'personal_gender' => 'required',
            'personal_smoker' => 'required'
        ]
    ];

Controller

$post = new Post(Input::all());

if($post->isValid('set_up_all', false)) {
  return 'It passed validation';
} else {
  return 'It failed validation';
}

In the above example, it works well in validating against the set_up_all ruleset. Now I would like to combine several rulesets and validate against all of them together.

According to the documentation, the package offers a way to merge rulesets. I just can't figure out how to integrate the example provided into my current flow.

According to the docs, I need to implement this line:

$mergedRules = $post->mergeRulesets('set_up_all', 'set_up_property_room', 'set_up_property');


This was my attempt, but it didn't work:

if($mergedRules->isValid()) { ...

I get the following error:

Call to a member function isValid() on array


I also tried this, but that didn't work either:

if($post->isValid($mergedRules)) { ...

I get the following error:

array_key_exists(): The first argument should be either a string or an integer


Any suggestions on how I would implement the merging rulesets?

zeckdude
  • 15,877
  • 43
  • 139
  • 187
  • I believe the method is named `mergeRules()` and not `mergeRulesets()` – silkfire Feb 13 '15 at 11:32
  • When I try mergeRules(), I get the following error: "Call to undefined method Illuminate\Database\Query\Builder::mergeRules()". Why did you think that is the case? – zeckdude Feb 13 '15 at 22:04

2 Answers2

1

From what I can see - mergeRulesets() returns an array of rules.

So if you do this - it might work:

$post = new Post(Input::all());
$post->setRules($post->mergeRulesets('set_up_all', 'set_up_property_room', 'set_up_property'));
if($post->isValid()) { 
     ///
}
Laurence
  • 58,936
  • 21
  • 171
  • 212
1

I've released an update version of the package for Laravel 4.2 (0.10.7) which now allows you to pass your rules to the isValid() method to validate against them.

$post->isValid($mergedRules);

The other answers will work, but this syntax is nicer (and won't override the existing rules on the model).

Dwight
  • 12,120
  • 6
  • 51
  • 64