Laravel - 使用外部请求时POST数据为空

Ric*_*mes 5 php laravel

我是laravel的新手,我正在尝试实现一个简单的rest api.

我已经实现了控制器,并通过单元测试进行了测试.

我的问题是POST请求.

通过测试输入:json有数据,通过外部休息客户端返回null.

这是单元测试的代码

    $newMenu = array(
      'name'=>'Christmas Menu', 
      'description'=>'Christmas Menu',
      'img_url'=>'http://www.example.com',
      'type_id'=>1,
    );
    Request::setMethod('POST'); 
    Input::$json = $newMenu;
    $response = Controller::call('menu@index');
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

更新:

这真是让我疯狂

我已经实现了一个新的laravel项目,只需要这个代码:

路线

Route::get('test', 'home@index');
Route::post('test', 'home@index');
Run Code Online (Sandbox Code Playgroud)

控制器:

class Home_Controller extends Base_Controller {

    public $restful = true;
    public function get_index()
    {
        return Response::json(['test'=>'hello world']);
    }
    public function post_index()
    {
        return Response::json(['test'=>Input::all()]);
    }
}
Run Code Online (Sandbox Code Playgroud)

CURL电话:

curl -H "Accept:application/json" -H"Content-type: application/json" -X POST -d '{"title":"world"}' http://localhost/laravel-post/public/test
Run Code Online (Sandbox Code Playgroud)

响应:

{"test":[]}
Run Code Online (Sandbox Code Playgroud)

任何人都可以指出我的错误.

这实际上阻止了我使用laravel,我真的很喜欢这个概念.

Mar*_*tis 7

因为您将JSON作为您的HTTP正文发布,所以您无法使用Input :: all() ; 你应该使用:

$postInput = file_get_contents('php://input');
$data = json_decode($postInput, true);

$response = array('test' => $data);
return Response::json($response);
Run Code Online (Sandbox Code Playgroud)

你也可以使用

Route::any('test', 'home@index');
Run Code Online (Sandbox Code Playgroud)

代替

Route::get('test', 'home@index');
Route::post('test', 'home@index');
Run Code Online (Sandbox Code Playgroud)