Leandro Garcia
Leandro Garcia

Reputation: 3228

Validate laravel error

I am trying to use $this->validate helper in Lumen. However, on the request, I need to do $request->json()->all() instead of $request->all() only because I can't get the exact parameters and its value (even if the fields has value it will still mark it as failed) when I use the latter.

$request->json()->all() output:

array:6 [
  "username" => ""
  "first_name" => "asaas"
  "last_name" => ""
  "email_address" => ""
  "password" => ""
  "password_confirmation" => ""
]

$request->all() output:

array:1 [
  "{"username":"","first_name":"asaas","last_name":"","email_address":"","password":"","password_confirmation":""}" => ""
]

Now, when I do pass $request->json()->all() on the helper:

$this->validate($request->json()->all(), [
    'username' => 'required|min:2|max:20',
    'first_name' => 'required|max:50',
    'last_name' => 'required|max:50',
    'email_address' => 'required|email',
    'password' => 'required',
]);

It will throw an error:

Type error: Argument 1 passed to Laravel\Lumen\Routing\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in

as I expected, because the $request should be passed not the one with the json()->all(). What can I do to address the error?

Upvotes: 2

Views: 339

Answers (1)

Sandeesh
Sandeesh

Reputation: 11906

Use the validator like so.

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->json()->all(), [
    'username' => 'required|min:2|max:20',
    'first_name' => 'required|max:50',
    'last_name' => 'required|max:50',
    'email_address' => 'required|email',
    'password' => 'required',
]);

Then handle the validation check

if ($validator->fails()) {
    return response()->json($validator->errors(), 422);
}

Or

$this->validateWith($validator);

Upvotes: 2

Related Questions