0

I would like to add custom validations rules on my Laravel Controller:

  • The container exists in the database
  • The logged user is owner of the resource

So I wrote this:

public function update($id, Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|unique:stock.containers|max:255'
    ]);

    $container = Container::find($id);

    if(!$container)
    {
        $validator->errors()->add('id', 'Not a valid resource');
    }

    if($container->owner_id != user_id())
    {
        $validator->errors()->add('owner_id', 'Not owner of this resource');
    }

    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);  //i'm not getting any
    }
}

Unfortunately the $validator->errors() or even $validator->addMessageBag() does not work. I noticed $validator->fails() clears the error messages and adding an error will not make the validation to fail.

What is the proper way to achieve this?

4
  • 1
    This is the correct way. Commented Jun 6, 2019 at 12:34
  • Well, then how do you apply this rule. The rule does not know the id of the resource and the rule does not apply to any value in the request... Commented Jun 6, 2019 at 12:35
  • You are using a wrong approach I believe. Because you can use the exists on the validator to make sure that the resource exists, but then you need to use a policy which will authorize the user for using the resource. Commented Jun 6, 2019 at 12:40
  • @nakov, Yes I can use the exists, but I don't have the $id of my resource, so I cannot check if it exists :( Commented Jun 6, 2019 at 12:47

1 Answer 1

1

Then you can use after:

public function update($id, Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|unique:stock.containers|max:255'
    ]);

    $validator->after(function($validator) use($id) {
        $container = Container::find($id);

        if(!$container)
        {
            $validator->errors()->add('id', 'Not a valid resource');
        }

        if($container->owner_id != user_id())
        {
            $validator->errors()->add('owner_id', 'Not owner of this resource');
        }
    });

    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);  //i'm not getting any
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your suggested solution is not working. laravel does not come in $validator->after(function($validator) use($id) { function. I have added a echo 'test';exit; before $container = Container::find($id); line but nothing is working. Any suggestion will be welcomed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.