Raja Abbas Raja Abbas - 3 years ago 224
Javascript Question

Laravel - Remove JSON header before saving to DB

I am fairly new to Laravel and Json.

I am looking to save JSON data directly to MYSQL table. Everything is working fine but this is the output I am getting which is being stored:

HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type: application/json
Date: Sun, 01 Oct 2017 04:10:34 GMT

{"_token":"53jnwIYCnLu1jeHdSVcL75Mgw2OD6RmZAh7Ojdyy","name":"adfadfdafd"}


I would like this to be the output saved in the db and everything else ignored:

{"_token":"53jnwIYCnLu1jeHdSVcL75Mgw2OD6RmZAh7Ojdyy","name":"adfadfdafd"}


Here is my controller:

public function addleads(Request $request)
{
$lead = new Lead;
$lead->lead_data = response()->json($request);
$lead->save();
}


View

<!-- load jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<!-- provide the csrf token -->
<meta name="csrf-token" content="{{ csrf_token() }}" />
<input class="name"></input>
<button class="postbutton">Post via ajax!</button>
<script>
$(document).ready(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(".postbutton").click(function(){
$.ajax({
/* the route pointing to the post function */
url: "{{ route('addleads') }}",
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN, name:$(".name").val()},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(JSON.parse(data));
}
});
});
});
</script>

Answer Source

based on your code, you can use this

public function addleads(Request $request)
{
    $lead = new Lead;
    $lead->lead_data = response()->json($request)->getContent();
    $lead->save();   
}

if you are not actually want to get response json, but request json, you can call $request->json() or json_encode($request->all())

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download