andersao / laravel-validator

Laravel Validation Service
http://andersao.github.io/laravel-validator
MIT License
412 stars 82 forks source link

Create an specific rule #23

Closed golinmarq closed 8 years ago

golinmarq commented 8 years ago

Right now, I'm using this package with l5-repositories. I need to create a custom method in my repository and request validation to it.

My CountryValidator seems like

protected $rules = [
    ValidatorInterface::RULE_CREATE => [
      'iso'=>'required|string|unique:countries|max:3',
      'title'=>'required|string|unique:states|max:50'
    ],
    ValidatorInterface::RULE_UPDATE => [
      'iso'=> 'string|max:3|unique:countries,iso',
      'title'=>'string|max:50|unique:countries,title',
    ],
    'ADD_STATES' => [
      'states' => 'required|array',
      'states.*.title' => 'required|string|max:50'
    ]
  ];

And my controller looks like:

public function addStates(CountryUpdateRequest $request, $id)
  {
    try {
      $this->validator->with($request->all())->passesOrFail(CountryValidator::ADD_STATES);

      $country = $this->repository->addStates($request->all(), $id);

      $response = [
        'message' => 'States added to the country.',
        'data'    => $country->toArray(),
      ];

    } catch (Exception $e) {

      if ($request->wantsJson()) {

        return response()->json([
          'error'   => true,
          'message' => $e->getMessageBag()
        ]);
      }
    }

But when I send a invalid request (i.e. {}) the validator doesn't works and throws a passOrFail exception. What can it be?

tucq88 commented 8 years ago

You should use $this->validator->with($request->all())->passesOrFail('ADD_STATES'); instead of calling static variable

golinmarq commented 8 years ago

@tucq88 thanks, but should I do this even when I declare a constant called ADD_STATES?

tucq88 commented 8 years ago

I think it's not necessary to use a constant for that, if you dig deeper to the source, you can see that 2 original const are just simple string. And I see that their purpose is for only getting rules list, so I think using raw string is fine.