Respect\Validation\Validator. I have a validator class validator.php
<?php
namespace app\http\validations;
use Respect\Validation\Validator as Respect;
use Respect\Validation\Exceptins\NestedValidationException;
class Validator {
protected $errors = [];
public function validate($request, array $rules){
foreach ($rules as $field => $rule) {
try{
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $ex) {
$this->errors[$field] = $ex->getMessages();
}
}
return $this;
}
public function failed(){
return !empty($this->errors);
}
}
Then I'm using this validation in the controller and here is my controller:
<?php
namespace app\http\controllers\v1;
use Slim\Http\Request;
use Slim\Http\Response;
use Respect\Validation\Validator as v;
use app\providers\v1\CompanyServiceProvider;
class CompanyController extends BaseApiController {
public $companyServiceProvider;
public function __construct() {
$this->companyServiceProvider = new CompanyServiceProvider();
}
public function saveBasicDetails(Request $request, Response $response) {
$validator = new \app\http\validations\Validator();
$validation = $validator->validate($request, [
'company_name' => v::notEmpty()->alpha()
]);
if($validation->failed()){
print_r($validation); die;
}
$result = $this->companyServiceProvider->saveBasicDetails($request);
return BaseApiController::returnResponse($response, $result);
}
}
Here is my route, I'm calling saveBasicDetails function from the route.
$app->post('/save-basic-details', \app\http\controllers\v1\CompanyController::class. ':saveBasicDetails');
I'm getting following error : These rules must pass for Company_name
I wanted to return validation errors in JSON.
In the controller you have to inject the container in the constructor, then define a getter to get your validator. check this link, in slim so far there is nothing like symfony autowire you have to explicitly inject the container and get the service you need afaik. Check this code below will help you!
//use Psr\Container\ContainerInterface;
/**
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
//Then define a getter
/**
* @return Validator
*/
protected function getValidator()
{
if (!$this->validator instanceof Validator) {
$this->validator = $this->container->get('Validator');
}
return $this->validator;
}
//Then access the validator
$this->getValidator()->validate...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With