0

Is it possible to use Laravels validate function to validate an array, and if so how?

I'm not interested in validating input or a request, I just wanna use Laravels great validation syntax on a completely ordinary array.

Example

$arr = array(
    'name' => 'David',
    'year' => 1986,
    'score' => 532
    );

$this->validate($arr, [
    'name' => 'required',
    'year' => 'numeric',
    'score' => 'required|numeric'
    ]);

This will throw an error

Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request

  • Laravel version: 5.1
  • PHP version: 7.1
0

3 Answers 3

2

You may use

$arr = array(
    'name' => 'David',
    'year' => 1986,
    'score' => 532
    );

$validator = Validator::make($arr, [
    'name' => 'required',
    'year' => 'numeric',
    'score' => 'required|numeric'
    ]);

and

if ($validator ->passes()){
/* True condition here*/
}
Sign up to request clarification or add additional context in comments.

3 Comments

D'oh. Obviously. Thank you - will accept your answer when I can
@Daniel OK. Did I get your question correctly? Or am I missing something?
This is exactly what I was looking for
0

$this->validate() method requires 'Request' as first argument. To use $this->validate() method you should merge request data before you call $this->validate().

$request->merge(array(
    'name' => 'David',
    'year' => 1986,
    'score' => 532
));

$this->validate($request->only(['name', 'year', 'score']), [
    'name' => 'required',
    'year' => 'numeric',
    'score' => 'required|numeric'
]);

P.S. Don't forget to inject Request service to your method.

Comments

0
$validator = Validator::make(
        $arr,
        array(
            'name' => 'required',
            'year' => 'numeric',
            'score' => 'required|numeric'
        )
    );

    if ($validator->fails()) {
        $errors = $validator->errors();
        print_r($errors);
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.