Use "$this" with rules for validation


Im having som issues with using $this and models in my small project. I don’t really fully understand this with injection and how everything really works, but unfortunately I have implemented way to much to try to reduce the code.

Im trying to call a function in a model from a “Rule”. Look at this line here. That function is trying to call doesEmailAlreadyExist() in the UserModel. The UserModel is injected into the $container here.

But the EmailAvailable rule doesn’t have $container

namespace App\Validation\Rules;
use Respect\Validation\Rules\AbstractRule;
class EmailAvailable extends AbstractRule
    public function validate($input)
        return $this->UserModel->doesEmailAlreadyExist($input);

So I’m receiving

Notice: Undefined property: App\Validation\Rules\EmailAvailable::$UserModel in app/Validation/Rules/EmailAvailable.php on line 11

Help is much appreciated!

Hi Johan, You are going to want to post in the Respect forms… This really has nothing to do with Slim… Although someone might be able to help you, I cannot guarantee it.

1 Like

Thanks for your response!

But I think it really not a Respect error.

The thing is that i can’t use the UseModel from Respect\Validation. Im having some problems to inject the UserModel into that class.

Yes, and that is a problem with your configuration of Respect, not with Slim.

Slim’s conatainer maintains objects for your application. You are responsible for configuring all of your dependencies and this error shows that Respect is not configured properly and that is outside our domain of support…

It looks like you are trying to create your own custom rule.

The UserModel isn’t set anywhere in your code which is why its throwing an error.

I have no idea how DI works in Respect, but I suspect you can add a setter to set the UserModel property, and call that before you attempt to validate.

1 Like