Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - POST data is null when using external request

Tags:

php

laravel

I'm new to laravel, and I'm trying to implement a simple rest api.

I have the controller implemented, and tested via unit testing.

My problem is with the POST request.

Via the tests Input:json has data, via an external rest client it returns null.

This is the code on the unit test

    $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');

What am I doing wrong?

UPDATE:

This is realy driving me crazy

I've instanciated a new laravel project and just have this code:

Routes

Route::get('test', 'home@index');
Route::post('test', 'home@index');

Controller:

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()]);
    }
}

CURL call:

curl -H "Accept:application/json" -H"Content-type: application/json" -X POST -d '{"title":"world"}' http://localhost/laravel-post/public/test

response:

{"test":[]}

Can anyone point me to what is wrong.

This is really preventing me to use laravel, and I really liked the concept.

like image 283
Ricardo Gomes Avatar asked Mar 28 '13 01:03

Ricardo Gomes


3 Answers

Because you are posting JSON as your HTTP body you don't get it with Input::all(); You should use:

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

$response = array('test' => $data);
return Response::json($response);

Also you can use

Route::any('test', 'home@index');

instead of

Route::get('test', 'home@index');
Route::post('test', 'home@index');
like image 130
Marius Kažemėkaitis Avatar answered Oct 11 '22 21:10

Marius Kažemėkaitis


If you use : Route::post('test', 'XYZController@test');
Send data format : Content-type : application/json
For example : {"data":"foo bar"}

And you can get the post (any others:get, put...etc) data with :

Input::get('data');

This is clearly written in here : http://laravel.com/docs/requests . Correct Content-type is very important!

I am not sure your CURL call is correct. Maybe this can be helpful : How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?

I am using Input::get('data') and it works.

like image 33
M.Gökay Borulday Avatar answered Oct 11 '22 23:10

M.Gökay Borulday


Remove header Content-type: application/json if you are sending it as key value pairs and not a json

like image 36
Rayiez Avatar answered Oct 11 '22 21:10

Rayiez