1

I have been stuck on that issue for a little while, no other question on SO helped me.

I am using Laravel 5.1 and phpunit to test a restful controller. My testing code looks as such:

$this->post('/api/book', [ 'title' => 'my book'])
  ->assertResponseOk();

And the target controller has, among others, the following code:

Log::debug('title: ' . $request->json('title'));

i.e. on the testing side I expect to use the TestCase::post() method to send a request and on the server side I expect to use the Request::json() method to read from the request. However when I look at the logs I see the following empty string

[2015-10-31 17:26:01] testing.DEBUG: title:   

This is showing that either my testing code is not setting the right data in the request or that my server code is not reading the request properly. By the way, the server is failing a bit further as well, reflecting the missing title value in the logs.

I am also using a Firefox plugin, RESTClient, to manually test my web app and I had to set properly the body (using double-quotes around the title key, respecting strictly the JSON specs) to make sure the server code work. So the exact format is a trail I followed, without success so far.

So my question is, what is the most recommended code to use for a RESTful controller on the testing and on the server sides, in Laravel 5.1?

1 Answer 1

1

The reason your log is empty is because this call $request->json('title') actually returns an array, not a string.

https://github.com/illuminate/http/blob/master/Request.php#L552

The correct way of accessing the key is like so:

Log::debug('title: ' . $request->title);

As described here:

http://laravel.com/docs/5.1/requests#retrieving-input

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

2 Comments

That sounds interesting, when submitting the request through the test the code $request->title returns the title, while when submitting the request through my browser's plugin the code $request->json('title') returns the title (and $request->title also works if I set the content-type properly). Thanks for the help, but that leaves me dubious. Especially as I have never heard of any concept such as HTTP request "input".
Right. I think the term "input" refers to input data as in "form input" data, which does sound a little off in a rest context I guess, yeah...

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.