16

I need to validate an array but without a request. In laravel docs validation is described like this:

$validator = Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);

But I can't use $request because the data comes from an external api and the validation is not inside a controller. How can I validate this array? For example:

$validatedData = validate([
    'id' => 1,
    'body' => 'text'
], [
    'id' => 'required',
    'body' => 'required'
]);
user3743266
  • 1,124
  • 4
  • 16
  • 28

5 Answers5

15

Should be. Because $request->all() hold all input data as an array .

$input = [
    'title' => 'testTitle',
    'body' => 'text'
];

$input is your custom array.

$validator = Validator::make($input, [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);
Erenor Paz
  • 3,061
  • 4
  • 37
  • 44
Ariel Pepito
  • 619
  • 4
  • 13
15

Validator::make expects array and not a request object. You can pass any array and implements the rules on it.

Validator::make(['name' => 'Tom'], ['name' => 'required', 'id' => 'required']);

And it will validate the array. So $request object is not necessary.

Muhammad Nauman
  • 1,249
  • 8
  • 10
12

You can achieve this by create request object like so:

$request = new Request([
    'id' => 1,
    'body' => 'text'
]);

$this->validate($request, [
    'id' => 'required',
    'body' => 'required'
]);

and thus you will get all the functionality of the Request class

Amr Aly
  • 3,871
  • 2
  • 16
  • 33
4

$request->all() is array not request object. This code will work:

$data = [
    'id' => 1,
    'body' => 'text'
];

$validator = Validator::make($data, [
    'id' => 'required',
    'body' => 'required',
]);
Anas K
  • 61
  • 1
  • 3
0

You can also merge data with the request object:

$data = ['id' => 1];
$request->merge($data);

Then validate as per usual.

omarjebari
  • 4,861
  • 3
  • 34
  • 32