3

How do I pass the "Accept: application/json" in request when testing:

for eg:

$response = $this->post($route, $data, ['Accept: application/json']);

OR

$response = $this->call('post' $route, $data, [], [], ['Accept: application/json']);

I want to invoke $this->wantsJson() in the FormRequest class:

/**
     * Get the proper failed validation response for the request.
     *
     * @param  array  $errors
     * @return \Symfony\Component\HttpFoundation\Response
     */
    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);
    }

1 Answer 1

4

You can use $this->json().

Visit the given URI with a JSON request.

Here's a link from Laravel's API:

Laravel 5.1 API

Laravel 5.2 API

Edit: For Laravel 7, you can visit their docs for Testing JSON APIs.

Sign up to request clarification or add additional context in comments.

4 Comments

is this available in 5.1?
@IvankaTodorova - Links are no longer valid. Any for Laravel 7 or upcoming 8?
@s3c Updated my answer with their docs for Laravel 7 & posting json to a route and it is the same for Laravel 8. (Also it's no longer upcoming, as it was released yesterday AFAIK). :)
@IvankaTodorova Yes, it was released sometime between my comment and two hours later. I wanted to say it just came out, but I'd be lying at that point in time. Thank you for the link. BTW, the two links for Laravel 5 are still dead so you might as well remove them if not find working ones. Upvoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.