54

I'm a Laravel newbie and I'm converting a php/jquery app to Laravel. The original code used a JSON array with an ajax POST, which was retrieved like this:

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

I'm doing much the same thing on the POST side, but I don't see any data coming through in my Laravel $request collection. Is there something special that I need to do to retrieve JSON data structured like this:

[
    { "name": "John", "location": "Boston" }, 
    { "name": "Dave", "location": "Lancaster" }
]

Here is my jQuery ajax POST code (with hard coded data)

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    dataType: "json",
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

Here is the code in my Controller that receives the POST

public function store(Request $request)
{
    dd($request->all());
}

But all I get is:

[]

Any ideas on how I can retreive my data?

6 Answers 6

73

You need to change your Ajax call to

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    contentType: "json",
    processData: false,
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

change the dataType to contentType and add the processData option.

To retrieve the JSON payload from your controller, use:

dd(json_decode($request->getContent(), true));

instead of

dd($request->all());
3
  • 2
    Sadly, I still don't get any data in my Laravel Controller - just []. However I can see that the headers change from Form Data to Request Payload
    – Adam
    Commented Oct 8, 2015 at 5:27
  • 2
    I have updated my response, you need to change the way you get the input in the controller, too.
    – Hieu Le
    Commented Oct 8, 2015 at 5:58
  • I've been back to this comment many times over the last few years, and I really appreciate it. Just wanted to say thanks. Commented Dec 8, 2023 at 7:09
36
 $postbody='';
 // Check for presence of a body in the request
 if (count($request->json()->all())) {
     $postbody = $request->json()->all();
 }

This is how it's done in laravel 5.2 now.

1
  • 2
    Thank you so much :), I was trying to use this with the JS fetch API
    – undefined
    Commented Sep 19, 2018 at 10:38
8

Just a mention with jQuery v3.2.1 and Laravel 5.6.

Case 1: The JS object posted directly, like:

$.post("url", {name:'John'}, function( data ) {
});

Corresponding Laravel PHP code should be:

parse_str($request->getContent(),$data); //JSON will be parsed to object $data

Case 2: The JSON string posted, like:

$.post("url", JSON.stringify({name:'John'}), function( data ) {
});

Corresponding Laravel PHP code should be:

$data = json_decode($request->getContent(), true);
2
  • how do you parse in php controller {name:'John'} the name? $data->name ?
    – t q
    Commented Jul 24, 2020 at 19:01
  • What does the true do here? I couldn't figure it out from the documentation on json_decode. Commented Feb 22, 2022 at 0:44
5

You can use getContent() method on Request object.

$request->getContent() //json as a string.
1
  • Answers should always come with some explantion
    – nbk
    Commented Jan 28, 2020 at 23:10
4

As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.

Retrieving JSON Input Values

When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig deeper into JSON arrays:

$name = $request->input('user.name');

https://laravel.com/docs/5.2/requests

As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    dataType: "json",
    contentType: "application/json",
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

By fixing the AJAX call, $request->all() should work.

1
  • then how can i parse "name" and "location" after $request->all()?
    – t q
    Commented Jul 24, 2020 at 19:08
0

My jQuery ajax settings:

        $.ajax({
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        url: url,
        dataType: "json",
        type: "post",
        data: params,
        success: function (resp){
            ....
        },
        error: responseFunc
    });

And now i am able to get the request via $request->all() in Laravel

dataType: "json"

is the important part in the ajax request to handle the response as an json object and not string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.