Home » Php » Laravel testing, get JSON content

Laravel testing, get JSON content

Posted by: admin October 29, 2017 Leave a comment


In Laravel’s unit test, I can test a JSON API like that:

$this->post('/user', ['name' => 'Sally'])
        'created' => true,

But what if I want to use the response. How can I get the JSON response (as an array) using $this->post()?


Currently in 5.3 this is working…

$content = $this->get('/v1/users/1')->response->getContent();

It does break the chain, however since response returns the response and not the test runner. So, you should make your chainable assertions before fetching the response, like so…

$content = $this->get('/v1/users/1')->seeStatusCode(200)->response->getContent();


Proper way to get the content is:

$content = $this->get('/v1/users/1')->decodeResponseJson();


I hit a similar problem and could not get $this->getResponse()->getContent() working with the built in $this->get() method. I tried several variations with no success.

Instead I had to change the call to return the full http response and get the content out of that.

// Original (not working)
$content = $this->get('/v1/users/1')->getContent();

// New (working)
$content = $this->call('GET', '/v1/users/1')->getContent();


I like to use the json method when working with json, instead of ->get()

$data = $this->json('GET', $url)->seeStatusCode(200)->decodeResponseJson();