Laravel: How do I save a JSON object to MYSQL database? - php

I want to post data from Frontend to MYSQL database in the backend using Laravel API. I tried the following code, but it outputs a 500: Internal Server Error while trying to post.
public function postOrder(Request $request)
{
/*
$request is a JSON Object which looks like
{"order":{"table_id":2,"food_id":4,"status":1}}
*/
$order = new Order();
$order->table_id = $request->order->table_id;
$order->food_id = $request->food_id;
$order->user_id = $request->user_id;
$order->status = $request->status;
$order->save();
return response()->json(['message' => 'Order Added'], 201);
}
Should I json_decode($request)? How?
When I error_log($request), here's what I get:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Connection: keep-alive
Content-Length: 60
Content-Type: application/json
Host: localhost:8000
Origin: http://localhost:8100
Referer: http://localhost:8100/
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML
, like Gecko) Chrome/55.0.2883.87 Safari/537.36
X-Xsrf-Token: eyJpdiI6IlJpNVV1ejhZTDVaSnVcL09lVkFIZER3PT0iLCJ2YWx1ZSI6IjNFK0
NnSXFsczd1eGJBRjZiZFc3U3lBUE9jR1lNZ0hSN0ZWNVpyWHlyWGE1TVZvZW9vK1F0eExXVjdkQzdPS
nBISEM3UXBINGQxZ09jTCttQ0huYmlnPT0iLCJtYWMiOiJmZWNiMTY1NTJjNjYyNDZjM2Q3YTE2N2Jl
NWNmYjgwYmNiMTlkNThjYWQ2NjEyYjk3YzQ4ZTVkYjQwMzFjY2VlIn0=
{"order":{"table_id":2,"food_id":4,"time":"333","status":1}}

You need to use json_decode() to get an associative array:
$json = '{"order":{"table_id":2,"food_id":4,"time":"333","status":1}}';
$array = json_decode($json, true);
var_dump($array['order']); //Here you can see that it is an associative array with the needed values now
Then you can create a model based on it.
$order = Order::create($array['order']);

that could be the solution:
json_decode($request, true)['order']['table_id']

Related

Is it possible to get ALL response headers from from Apache using PHP?

I get the request headers from the browser like this.
<?php
$DataFromBrowser='';
$DataToBrowser='';
$headers = getallheaders();
foreach($headers as $key=>$val){
$DataFromBrowser = $DataFromBrowser . $key . ': ' . $val . "\n";
}
//echo get_raw_http_request();
echo "Data from browser";
echo '<textarea rows="12" style="width:100%;">' . $DataFromBrowser . '</textarea>';
?>
And the output will look like this.
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,/;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: foo=bar
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Now I want to do exactly the same but for the response headers from the server. I'm aware I can do the following but it will create another connection I need the response headers of the current served page.
<?php
$URL = 'https://www.google.com';
$headers = get_headers($URL);
foreach($headers as $value) {
echo $value;
echo "<br>";
}
?>
If I change the above to http://127.0.0.1 It get's it self in a deadlock and will loop until it bombs out.
The response headers should look like this.
HTTP/1.1 200 OK
Date: Wed, 08 Jun 2022 16:53:45 GMT
Server: Apache/2.4.46 (Win64) OpenSSL/1.1.1j PHP/8.0.3
X-Powered-By: PHP/8.0.3
Content-Length: 589
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

php does not recognize JSON post message

Im struggling with sending JSON data via XMLhttp post request.
Data is:
"{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"
JS code is:
var reqData = {
reqType : "post", //isDateRequested : 1,
reqName : "getCurrTemp",
reqPayload : ""
};
var dataToSend = {'reqData' : reqData };
var jData = JSON.stringify(dataToSend);
alert(jData);
var oReq = new XMLHttpRequest();
oReq.onload = function() {
data = JSON.parse(this.responseText);
};
oReq.open("POST", "handleRequests.php", true);
oReq.send(jData);
Im having problem on php side, looks like server does not recognize JSON, or even message lost...
I used wireshark to sniff traffic:
POST /autHouse/handleRequests.php HTTP/1.1
Host: 192.168.0.12
Connection: keep-alive
Content-Length: 70
Origin: http://192.168.0.12
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: http://192.168.0.12/autHouse/ah.html
Accept-Encoding: gzip, deflate
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}HTTP/1.1 200 OK
Date: Tue, 19 Jan 2016 10:53:22 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.45-0+deb7u2
Content-Length: 84
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html
string(70) "{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"
here is php code:
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData'], true);
$reqType = $reqData["reqType"];
$reqName = $reqData["reqName"];
and realted php error log:
[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] , referer: http://192.168.0.12/autHouse/ah.html
[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] PHP Notice: Undefined index: reqData in /var/www/autHouse/handleRequests.php on line 15, referer: http://192.168.0.12/autHouse/ah.html
Can you please tell me why php complians while im sending proper JSON data?
regards
J.
Try this
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "handleRequests.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(jData);
You have missed a level in the resulting array.
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData'], true);
$reqType = $reqData['reqData']["reqType"];
$reqName = $reqData['reqData']["reqName"];
If you prefer using the objects that the data is being passed as rather than converting the objects to arrays you can do
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData']);
$reqType = $reqData->reqData->reqType;
$reqName = $reqData->reqData->reqName;

How do I get twitter posts?

I am trying to get twitter posts following this tutorial:
https://www.youtube.com/watch?v=tPrsVKudecs
there aren't a lot of tutorials regarding this online, and twitters console doesn't support running queries anymore as far as I understood.
any idea why this is happening?
This is the output I get in the Chrome "Network":
Remote Address:54.666.666.666:80
Request URL:http://666.com/yh/test/tweets_json.php
Request Method:GET
Status Code:500 Internal Server Error
Response Headers
view source
Connection:close
Content-Length:0
Content-Type:text/html
Date:Mon, 15 Jun 2015 13:51:40 GMT
Server:Apache/2.4.7 (Ubuntu)
X-Powered-By:PHP/5.5.9-1ubuntu4.5
Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:666.com
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
Any ideas why this is happening?
Is there a better simple way to do it?
EDIT:
tweets_json.php
<?php
require 'tmhOAuth.php'; // Get it from: https://github.com/themattharris/tmhOAuth
// Use the data from http://dev.twitter.com/apps to fill out this info
// notice the slight name difference in the last two items)
$connection = new tmhOAuth(array(
'consumer_key' => '',
'consumer_secret' => '',
'user_token' => '', //access token
'user_secret' => '' //access token secret
));
// set up parameters to pass
$parameters = array();
if ($_GET['count']) {
$parameters['count'] = strip_tags($_GET['count']);
}
if ($_GET['screen_name']) {
$parameters['screen_name'] = strip_tags($_GET['screen_name']);
}
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else {
$twitter_path = '1.1/statuses/user_timeline.json';
}
$http_code = $connection->request('GET', $connection->url($twitter_path), $parameters );
if ($http_code === 200) { // if everything's good
$response = strip_tags($connection->response['response']);
if ($_GET['callback']) { // if we ask for a jsonp callback function
echo $_GET['callback'],'(', $response,');';
} else {
echo $response;
}
} else {
echo "Error ID: ",$http_code, "<br>\n";
echo "Error: ",$connection->response['error'], "<br>\n";
}
// You may have to download and copy http://curl.haxx.se/ca/cacert.pem
tmhOAuth.php: https://github.com/themattharris/tmhOAuth/blob/master/tmhOAuth.php
and this pem key: http://curl.haxx.se/ca/cacert.pem
All three in the same folder
In the tutorial it should run the query and get the json output.
I get a blank page.

get PHP custom response headers

I´m sending an ajax request with a custom header called Authorization,
and I'm trying to get that header with PHP
if (!function_exists('getallheaders'))
{
function getallheaders()
{
$headers = array();
foreach ($_SERVER as $k => $v)
{
if (substr($k, 0, 5) == "HTTP_")
{
$k = str_replace('_', ' ', substr($k, 5));
$k = str_replace(' ', '-', ucwords(strtolower($k)));
$headers[$k] = $v;
}
}
return $headers;
}
}
$val = getallheaders();
echo $val;
and I get all the headers but not the custom one
val: Object{
Accept: "application/json, text/plain, */*"
Accept-Encoding: "gzip, deflate, sdch"
Accept-Language: "es-ES,es;q=0.8,en;q=0.6"
Connection: "keep-alive"
Host: "www.localhost.com"
Origin: "http://localhost"
Referer: "http://localhost/gestion/"
User-Agent: "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
}
Any clues why I'm not getting header Authorization?
For custom headers the $_SERVER global in php documentation state that
There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those
so try to use apache_request_headers which may help you if your working with apache as a server
Server Quote
apache_request_headers

Apache 301 status when using put method

Develop a simple backbone and php application but on a server i get 403 error
whenever i use a put method
Of course when using more traditional method such as get and post i do not get any problem.
Could any one advise on what is the specific settings to tune because on another server it work great.
My suspects are
apache configuration
php configuration
Thanks in advance.
Code Sample
PHP file
$this -> method = $GLOBALS['_SERVER']['REQUEST_METHOD'] ;
switch ( $this -> method ) {
case ( 'POST' ) :
foreach ( $_POST as $k => $v )
$data -> $k = $v ;
$data = $this -> save ($data) ;
$this -> output( $data ) ;
break
case ( 'PUT' ) :
$putdata = fopen("php://input", "r");
while ($d = fread($putdata, 1024))
$data .= $d ;
$data = json_decode( $data ) ;
$data = $this -> save ($data) ;
$this -> output( $data ) ;
break ;
case ( 'DELETE' ) :
$data = $this -> delete($data) ;
$this -> output( $data ) ;
break ;
case ('GET') :
default:
$data = $this -> retrieve () ;
$this -> output( $data ) ;
break ;
}
Note that backbone does not need form using jquery ajax to make an xhr request
arguments: {
0: {
contentType: "application/json"
data: {
"id":0,
"dat":"10-03-2014",
"title":"Bunk bed",
"current":false,
"enrole":[],
"result":"",
"starts":{"m":{},"f":{}},"sex":"m"}
}
dataType: "json"
emulateHTTP: false
emulateJSON: false
error: function (resp) { ... }
parse: true
processData: false
success: function (resp) { ... }
type: "PUT"
url: "event" // event is a folder with index.php
validate: true
}
}
Backbone.$.ajax.apply(Backbone.$, arguments);
Here is the request made by the browser
Request Method:PUT
Status Code:301 Moved Permanently
Request Headersview parsed
PUT /maa/event HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 123
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost
X-Requested-With: XMLHttpRequest
Content-Type: application/json
Accept: application/json, text/javascript, */*; q=0.01
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36
Referer: http://localhost/maa/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,fr;q=0.6,fr-FR;q=0.4
Request Payloadview parsed
{"id":0,"dat":"10-03-2014","title":"Acton Vale","current":false,"enrole":[],"result":"","starts":{"m":{},"f":{}},"sex":"m"}
Everything work except for the put which generates a 301 error

Categories