Store JSON with a resource controller in Laravel

I'm working on a restful API solution in Laravel. My problem is that I cannot make my store function accept JSON. In my store function I have the following code (based on this tutorial http://code.tutsplus.com/tutorials/laravel-4-a-start-at-a-restful-api-updated--net-29785):

public function store()
{
    $url = new Url;

    $url->url = Request::get('url');
    $url->description = Request::get('description');
    $url->save();


    return Response::json(array(
        'error' => false,
        'message' => 'test',
        'urls' => $url->toArray()),
        200
    );
}

When I send my data like this:

 curl -d "url=test&description=testing" localhost/api/v1/url

it works as expected and the record is inserted into my database.

However, when I try to post some JSON like this

curl -d '{"url":"test","description":"test"}' localhost/api/v1/url

I can't even return the data by using Request::get('url'). I've read here on SO that Input::all() or Input::json()->all() would work, but I still can't return the data i'm posting. Any ideas how I can access url and description when it is posted as JSON?


You're not using curl correctly to post a json, try this:

curl -X POST -H "Content-Type: application/json" -d '{"url":"test","description":"test"}' localhost/api/v1/url

If you are using a Windows client, you can use Postman (http://www.getpostman.com/), a Chrome plugin.

Configure it to:

1) POST

2) raw (and paste your json in the box)

3) Header: Content-Type Value: application/json

And to do your tests you can use a simple router like this:

Route::any('test', function() {

    Log::info(Input::all());

});

And execute

php artisan tail

To see what happens when you post.

链接地址: http://www.djcxy.com/p/8554.html

上一篇: PHP脚本中的PHP POST curl终端命令

下一篇: 在Laravel中存储带有资源控制器的JSON