Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CleytonBonamigo's avatar

Validation inside Controller

Hi, I'm building an API where methods in Controller are called by cURL. Well, the methods are create and view, and I'm trying to validate some fields, like Authentication by token.

Everything is alright with Auth, but, I'm tryin to validate some fields by http://laravel.com/docs/5.0/validation#form-request-validation.

Whenever I call the methos, it's redirect to homepage, not validating any field, even if I set the rule with 'required' and pass a null value for the field.

It's possible to validate a cURL request with form validating?

0 likes
7 replies
shahinul87's avatar

You can try this

$payload = $request->header('X-Auth-Token');
$user =  $userModel->where('api_token',$payload)->first();

    if(!$payload || !$user) {

        $response = Response::json([
            'error' => true,
            'message' => 'Not authenticated',
            'code' => 401],
            401
        );
CleytonBonamigo's avatar

Thanks, the authenticate method is ok, my problem is with the other fields, like an id. Well, I see in the documentation, the Form Request redirects to the previous page and throw the error. What I'm trying is to stop in controller and throw the error, and I think it's not possible, right?

pmall's avatar

@CleytonBonamigo If you specify with your request that you accept a json response the form request will not redirect back but return a json array of errors. It uses $request->wantsJson() internally.

1 like
CleytonBonamigo's avatar

@pmall Well, and when I put the code? In controller? I could change the response method, but I would like to do it your way.

bestmomo's avatar
Level 52

@CleytonBonamigo

Code is in core :

public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson())
    {
        return new JsonResponse($errors, 422);
    }

    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}

If you want to change it you must override this method in your form request.

pmall's avatar

@CleytonBonamigo No, not in your code, i think your cUrl request headers should specify it expect json as a response.

For example it works with jquery when you send an ajax request and set the type to json.

1 like
CleytonBonamigo's avatar

@pmall Thanks, I tried to do that, but I was forgetting one field in header, now it works perfectly, but I will have to change the response method.

@bestmomo Yeah, exactly what I did before and what I have to do now, unfortunately I will have to override this method to a custom response, thanks.

Please or to participate in this conversation.