when i want change get become post it not work well - laravel

i have problem when i want to change Get become Post.
when i use Get i can get the data
but when use post i cannot get the data please help me
i have change the web.php or routes become Post but i cannot get my data when i use post
i have change get become post in my web.php in my laravel. but the result not the same
this is my code in laravel
public function getHistoryEvent(Request $request) {
$consumer_data = array();
$consumer_data['consumer_key'] = request()->header('consumer-key');
$consumer_data['consumer_secret'] = request()->header('consumer-secret');
$consumer_data['consumer_nonce'] = request()->header('consumer-nonce');
$consumer_data['consumer_device_id'] = request()->header('consumer-device-id');
$consumer_data['consumer_url'] = __FUNCTION__;
$authController = new AppSettingController();
$authenticate = $authController->apiAuthenticate($consumer_data);
if($authenticate==1 || $authenticate==0){
$event = DB::table('u_history_events')
->select('u_history_events.history_events_id','u_history_events.events_image','u_history_events.events_description','u_history_events.date_create')
->where('u_history_events.events_id',$request->events_id)
->where('u_history_events.kode_customers',$request->kode_customer)
->get();
$responseData = array('success'=>'1', 'data'=>$event, 'message'=>"Success.");
}else{
$responseData = array('success'=>'0', 'data'=>array(), 'message'=>"Unauthenticated call.");
}
$orderResponse = json_encode($responseData);
print $orderResponse;
}
when use get i can get this data the result are :
{"success": "1",
"data": [
{"history_events_id": 2,
"events_image": "",
"events_description": "",
"date_create": "2019-05-11 10:59:01"
},
{
"history_events_id": 3,
"events_image": "",
"events_description": "",
"date_create": "2019-05-11 11:59:35"
}
}
but when i use post i only get
{"success":"1","data":[],"message":"Success."}

I am no Laravel expert, but according to the docs, looks like you have to explicitly define a route for the POST verb to your controller's method:
Route::post($uri, $callback);
Or according to Controllers docs:
// change <your path here> and <your method name> to your desired path and
// method names
Route::get('<your path here>', 'AppSettingController#<your method name>');
I also recommend you to read MDN's An overview of HTTP.

Related

google-cloud-php Document AI: INVALID_ARGUMENT

I am trying to use google-cloud-php to send documents to Google Document AI for processing.
Here is an example of my code:
require 'vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=[###].json');
use Google\Cloud\DocumentAI\V1\Document;
use Google\Cloud\DocumentAI\V1\DocumentProcessorServiceClient;
$document = array();
$document['mime_type'] = 'application/pdf';
$document['content'] = file_get_contents('file.pdf');
$inlineDocument = new Document($document);
$postBody = array();
$postBody['inlineDocument'] = $inlineDocument;
$postBody['skipHumanReview'] = true;
$documentProcessorServiceClient = new DocumentProcessorServiceClient();
$formattedName = $documentProcessorServiceClient->processorName('[###]', 'eu', '[###]');
$operationResponse = $documentProcessorServiceClient->processDocument($formattedName, $postBody);
I am passing my arguments according to following documents:
processDocument Documentation
Document Documentation
However, I get the following response:
Fatal error: Uncaught Google\ApiCore\ApiException: { "message": "Request contains an invalid argument.", "code": 3, "status": "INVALID_ARGUMENT", "details": [] } thrown in \vendor\google\gax\src\ApiException.php on line 139
For some reason, the following document mentions to pass one argument as "mimeType" instead of "mime_type" compared to the previous link:
https://cloud.google.com/document-ai/docs/send-request
I tried that as well but that throws an exception in the php class.
Any help would be greatly appreciated!
I was running into the same issue, the problem is when other region than 'us'. If so, you should specify the apiEndpoint:
$documentProcessorServiceClient = new DocumentProcessorServiceClient([
'apiEndpoint' => 'eu-documentai.googleapis.com'
]);

Strapi, use find to check if an object type field has a match in one of the properties

Let's say I have a field called user with a data that looks something like this
{
"id": "abc123",
"name": "John Smith"
}
I want to make a route where I can find where user.id equals, say, abc123 and should return the blogs that has a user with the id above
I've tried doing
async findByUser(ctx) {
let blogs = await strapi.services.blogs.find({
user: {id:ctx.params.id},
return blogs;
},
but that doesn't seem to work as it returns an empty array and isn't searching specifically in the id property. How do I do this using strapi?
edit: User is not an relation, it is an individual JSON field.
Okay, for querying a JSON object property, you will need to write a custom query. Look at the example below.
Implementation for PostGreSQL
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', '#>', `{"id": "${ctx.params.id}" }`);
// qb.where('user', '#>', `{"name": "${ctx.params.name}" }`);
})
.fetch();
return response.toJSON();
},
Implementation for SQLite
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', 'LIKE', `%"id":"${ctx.params.id}"%`);
})
.fetch();
return response.toJSON();
},
P.S: Just use fetch instead of fetchAll for consistency.
Hi there thanks to Salvino's help I think i am able to find a solution
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', 'LIKE', `%"id":"${ctx.params.id}"%`);
})
.fetchAll();
return response.toJSON();
},

Laravel query result, change the column name into numeric

I just wonder how to convert the key of query result into numeric. This is my query result for the example:
$result = [{
"lat": "43289043208",
"lng": "-3890423802"
},...]
What I want is
$result = [{
0: "43289043208",
1: "-3890423802"
},...]
Any helps would be appreciated.
You can use array_values() method.
And iterate the result array
$newArray = [];
foreach(json_decode($result) as $res)
{
$newArray[] = array_values($res);
}
Finally, I use this, and it solved for now
$table_data = DB::table($table)->select(DB::raw("$lat_field as '0'"), DB::raw("$lng_field as '1'"))->get();

Laravel: how to parse string to json

I've created this code from laravel:
public function findConfig($id)
{
$config = DB::table('configuration')
->join('model', 'model.configuration_id','=', 'configuration.id')
->select('configuration.id','configuration.description', 'model.name','configuration.price')
->where('configuration.id','=', $id)
->get();
$encode = json_encode($config, JSON_UNESCAPED_SLASHES);
$response = Response::make($encode, 200);
$response->header('Content-Type', 'application/json');
return $response;
}
then the return is somehow like this
[{
"id": "1",
"description": "{\"item\":[{'colours\":[\"red\",\"blue\",\"green\"]},{\"motors\":[ {\"name\":\"450W/48V\",\"price\":\"2,000\"},{\"name\":\"550W/48V\", \"price\":\"3,000\" }] } ]}",
"name": "k5-A",
"price": "300000"
},
{
"id": "1",
"description": "{\"item\":[{'colours\":[\"red\",\"blue\",\"green\"]},{\"motors\":[ {\"name\":\"450W/48V\",\"price\":\"2,000\"},{\"name\":\"550W/48V\", \"price\":\"3,000\" }] } ]}",
"name": "r-A",
"price": "300000"
}
]
How can I remove the slashes and instead of string as return type, it should be in JSON?
As lukasgeiter said, generally it isn't a good idea to store json in a db. It may get difficult to filter by that field.
If you decide to do so, and need to get the decoded data, you can use an accessor in the model. I don't know if it is the best practice. If the description is saved in the db as a json you can do this:
For the "configuration" table you may have a "Configuration" model (The official Laravel website recommends to name the table in plural, and the model in it's singular, like: table -> configurations and the model configuration). In that file you can add this:
public function getDescriptionAttribute($value)
{
return json_decode($value, true);
}
Now, the description field is returned as an array.
You can see more about accessors and mutators here: http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

Parse.com manipulate Response Object

I am trying to work Ember with Parse.com using
ember-model-parse-adapter by samharnack.
I add added a function to make multiple work search(like search engine) for which I have defined a function on cloud using Parse.Cloud.define and run from client.
The problem is the Array that my cloud response returns is not compatible with Ember Model because of two attributes they are __type and className. how can I modify the response to get response similar to that i get when I run a find query from client. i.e without __type and className
Example responses
for App.List.find() = {
"results":[
{
"text":"zzz",
"words":[
"zzz"
],
"createdAt":"2013-06-25T16:19:04.120Z",
"updatedAt":"2013-06-25T16:19:04.120Z",
"objectId":"L1X55krC8x"
}
]
}
for App.List.cloudFunction("sliptSearch",{"text" : this.get("searchText")})
{
"results":[
{
"text":"zzz",
"words":[
"zzz"
],
"createdAt":"2013-06-25T16:19:04.120Z",
"updatedAt":"2013-06-25T16:19:04.120Z",
"objectId":"L1X55krC8x",
"__type" : Object, //undesired
"className" : "Lists" //undesired
}
]
}
Thanks Vlad something like this worked for me for array
resultobj = [];
searchListQuery.find({
success: function(results) {
for( var i=0, l=results.length; i<l; i++ ) {
temp = results.pop();
resultobj.push({
text: temp.get("text"),
createdAt: temp.createdAt,
updatedAt: temp.updatedAt,
objectId: temp.id,
words: "",
hashtags: ""
});
}
In your cloud code before you make any response, create and object and extract from it the attributes/members you need and then response it. like so:
//lets say result is some Parse.User or any other Parse.Object
function(result)
{
var responseObj = {};
responseObj.name = responseObj.get("name");
responseObj.age = responseObj.get("age");
responseObj.id = responseObj.id;
response.success(responseObj);
}
on the response side you will get {"result": {"name": "jhon", "age": "26", "id": "zxc123s21"}}
Hope this would help you

Resources