Posting JSON To Laravel

Update: Laravel 5

Please note as of Laravel 5.0, the Input facade has been removed from the official documentation (and in 5.2 it was also removed from the list of default Facades provided) in favor of directly using the Request class that Input invokes, which is Illuminate\Http\Request.

Also, as of the Laravel 5.1 documentation, all references to the Request facade have been removed, again in preference of using the Illuminate\Http\Request instance directly, which it encourages you to do via dependency injection in either:

...your Controller Method:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function update(Request $request, $id)
    {
        $data = $request->json()->all();
    }
}

...or a Route Closure (as of 5.3):

use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
    $data = $request->json()->all();
});

json() and ParameterBag

It's worth noting that $request->json() returns an instance of Symfony\Component\HttpFoundation\ParameterBag, and that ParameterBag's ->all() method returns an associative array, and not an object as the OP expected.

So one would now fetch the rough equivalent of $_POST['id'] as follows:

$data = $request->json()->all();
$id = $data['id'];

`Input` and `Request` facades: Current Status

Both facades have been removed from the official documentation (as of 5.1), and yet they both also remain in the source code with no 'deprecated' label.

As mentioned earlier, Input was removed as a default facade ('alias') in 5.2, but as of 5.4, the Request facade remains a default.

This seems to imply that one could still use the Request facade to invoke methods on the Request instance (e.g. Request::json()), but that using dependency injection is simply now the officially preferred method.


NOTE: this answer is only applicable for old Laravel versions (4.2 and earlier)!

Laravel's Input::all method returns an associative array, not an object of PHP's stdClass.

$data = Input::all();
$data['id']; // The ID of the request

To expand (and correct) the above, in Laravel 5 you would retrieve JSON as shown:

public function handle_ajax(Request $request) {
    $data = (object) $request->json()->all();
    Clockwork::info($data->id);
}

In non-trivial examples you might want to also validate your input first.