0

I have this route in route/api.php:

Route::post('/register', 'LoginController@register');

My LoginController

class LoginController extends Controller {

public function register(Request $request) {
    $this->validate($request, // <-- using this will return the view
      // from **web.php** instead of the expected json response.
    [
        'email' => 'required|email',
        'firstName' => 'required|alpha_dash',
        'lastName' => 'required',
        'password' => 'required|confirmed',
    ]);

    $input = $request->all();
    //$plain_password = $input['password'];
    $input['uuid'] = uuid();
    $input['password'] = Hash::make($input['password']);

    $user = User::create($input);

    dd($errors);

    $response['succes'] = true;
    $response['user'] = $user;
    return response($response);
    }
}

Why does adding a validation call change the behaviour to returning my view / the wrong route. I want the api to validate my request too, not just my "frontend".

online Thomas
  • 8,864
  • 6
  • 44
  • 85

1 Answers1

1

When you use Laravel's validate method from controller it automatically handles/takes the step if the validation fails. So, depending on the required content type/request type, it determines whether to redirect back or to a given url or sending a json response. Ultimately, something like thos following happens when your validation fails:

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());
}

So, if the first if statement is true then you'll get a json response and it'll be true if you either send an ajax request or if you attach a accept header with your request to accept json response (When requesting from a remote server). So, make sure your request fulfills the requirements.

Alternatively, you can manually validate the request using the Validator component and return a json response explicitly if it fails.

The Alpha
  • 143,660
  • 29
  • 287
  • 307