Insert multiple json data into mysql database from postman using codeigniter api - php

I am tring to insert multiple data in db using postman but only single data is insetred successfully ,when inserting multiple data getting 500 error.Please help me on how can i insert multiple data in db.Any help would be highly appreciated.Thank you.
PostMan raw data:
[{
"total_sales":"14",
"total_product":"21",
"total_profit":"5099",
"total_distributor":14,
"total_ratail":40 },
{
"total_sales":14,
"total_product":21,
"total_profit":50,
"total_distributors":14,
"total_ratail":40 }
]
Below is my code:
public function create()
{
$model = new AdminModel();
print_r("total_sales");
$data = array(
'total_sales'=>$this->request->getVar('total_sales'),
'total_product'=>$this->request->getVar('total_product'),
'total_profit'=>$this->request->getVar('total_profit'),
'total_distributors'=>$this->request->getVar('total_distributors'),
'total_ratail'=>$this->request->getVar('total_ratail'),
);
$query = $model->where('id', $data['total_sales'])->find();
if(count($query)>0){
$model->update->where('id', $data['total_sales'])->find();
}
else{
$model->insert($data);
}
//$model->insert($data);
$response = [
'status' => 200,
'error' => null,
'messages' => [
'success' => 'Data Saved'
]
];
return $this->respondCreated($response);
}

You are adding an array of objects but the code is expecting only one object. That's why you are getting the error.
You have to modify your php code to accept an array and loop through them.

Related

Best way to store and load JSON from database in Laravel

I'm trying to store json into a db and load it back
I tried to store
{name: "John", age: 31, city: "New York"}
It stored correctly. I checked the db, it showed correctly.
{name: "John", age: 31, city: "New York"}
I kept getting on the view
"{name: \"John\", age: 31, city: \"New York\"}"
This is my code.
public function store()
{
$paste = new Paste;
$paste->uuid = Str::uuid()->toString();
$paste->data = trim(Request::get('data',''));
$paste->save();
return Redirect::to('/paste/'.$paste->uuid)->with('success', 'Created');
}
public function show($uuid)
{
$paste = Paste::where('uuid',$uuid)->first();
return response()->json($paste->data);
}
Any hints for me ?
Reproducible here
https://www.bunlongheng.com/paste
Try # 2
If I did this
public function show($uuid)
{
$paste = Paste::where('uuid',$uuid)->first();
return View::make('layouts.fe.pastes.show', get_defined_vars());
}
and in my view, I only have this 1 line
{!!$paste->data!!}
I get the same data as what I submitted now.
{name: "John", age: 31, city: "New York"}
BUT the browser detected it as text, not a response JSON which defeated the purpose of what I am trying to do.
Try # 3
public function show($uuid)
{
$paste = Paste::where('uuid',$uuid)->first();
return response()->json(stripslashes($paste->data));
}
result
"{name: \"John\", age: 31, city: \"New York\"}"
Try # 4
public function show($uuid)
{
$paste = Paste::where('uuid',$uuid)->first();
return View::make('layouts.fe.pastes.show', get_defined_vars());
}
view
{{ json_encode($paste->data, JSON_UNESCAPED_SLASHES) }}
result
"{name: \"John\", age: 31, city: \"New York\"}"
Try #5
I think the issue is lying on the storing ... not the loading and rendering.
I tried
return response()->json($paste);
My JSON parser detected it ...
{
"id": 11,
"status": 0,
"uuid": "0c40f97d-7d98-42c6-864e-71d3ed81eed3",
"name": "n6ou",
"password": "",
"expiration": "",
"type": "json",
"data": "{name: \"John\", age: 31, city: \"New York\"}",
"created_at": "2021-04-22T22:53:11.000000Z",
"updated_at": "2021-04-22T22:53:11.000000Z"
}
This is what I used to store
$paste->data = trim(Request::get('data',''));
$paste->save();
Try #6
For those of you that doubt my data/content
I've tried pasting the same line in Pastebin
It's cleaned, you can see below.
https://pastebin.com/raw/r9akUK1v
Database
In your database migrations add:
$table->json('data'); // Recommended. Supported in MySQL since version 5.7.8
or
$table->text('data');
The JSON column type is recommended as it allows you to do SQL queries on JSON data. See MySQL JSON Data Type
Model: Casting the Attribute
The next issue is that you need to be able to cast your data into a PHP array.
This is done by modifying the casts attribute in the model:
class Paste extends Model {
protected $casts = [
'data' => 'array'
];
}
See Array and JSON Casting for more information.
Now you can save data onto the attribute as a PHP array, and also assign it a PHP array.
$paste = Paste::first();
dump($paste); // Returns a PHP array
$paste->data = ['some-data' => 20, 'score' => 500];
$paste->save();
Internally, when it saves the data, it automatically would convert it into a JSON string and save it in the database in the correct format.
Store Method
When taking in input as JSON, it highly depends in how you want to pass the data,
1. Sending form data with JSON content type (recommended)
My recommendation is to send the entire data as JSON in the POST body like so:
Content-Type: application/json
Body:
{
"data": {
"name": "John",
"age": 31,
"city": "New York"
},
"someOtherField": "Hello!"
}
Your store() method should now be (I've also added validation code):
public function store()
{
$this->validate($request, [
'data' => ['required', 'array'],
'data.*.name' => ['required', 'string'],
'data.*.age' => ['required', 'int'],
'data.*.city' => ['required', 'string'],
]);
$paste = new Paste();
$paste->uuid = Str::uuid()->toString();
$paste->data = $request->post('data'); // No need to decode as it's already an array
$paste->save();
return Redirect::to("/paste/{$paste->uuid}")
->with('success', 'Created');
}
2. Sending form data with form params
If however you insist in sending data through query params or form params, note these can only send strings. Therefore you need to send an encoded version of the JSON string to persists data types, as follows:
Form Params:
- data: '{"name": "John", "age": 31, "city": "New York"}'
- someOtherField: "Hello!"
The store method will now look like this:
$this->validate($request, [
'data' => ['required', 'json'], // I'm unsure if data is required
]);
$data = json_decode($request->post('data'), true, JSON_THROW_ON_ERROR); // Needs to be decoded
// validate $data is correct
Validator::make($data, [
'name' => ['required', 'string'],
'age' => ['required', 'int'],
'city' => ['required', 'string'],
])->validate();
$paste = new Paste();
$paste->uuid = Str::uuid()->toString();
$paste->data = $data;
$paste->save();
return Redirect::to("/paste/{$paste->uuid}")
->with('success', 'Created');
Show Method
Your show method needs no changes:
public function show($uuid)
{
$paste = Paste::where('uuid', $uuid)->first();
return response()->json($paste->data);
}
1- Your column need to be of type json type
$table->json('data');
2- in your Model you need to cast your column to an array
protected $casts = ['data' => 'array'];
3- sending data value to your controller must be an array so you can use array Laravel validation on it:
[
'data' => 'required|array',
'data.*.name' => 'required'
....
]
4- when you store your data it will be parsed automatically and the same when you retrieve your data column it will be converted to an array
Using ->json() as the migration method to store JSON data (https://laravel.com/docs/8.x/migrations#column-method-json)
Refer to "Array & JSON Casting" (https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting) for how do you prepare the data
I know the answer is not in paragraphs as others, but I like to make it simple and straight. Is it the best solution? No one can tell you that nor prove that? Is this method going to work, no one can tell you that nor prove that, but at least it boosts up your success rate. Let me know if there is anything else I could help with! Good Luck
If you want to store data as json on DB and restore it just do the following (I always use this way):
1- Add your data to array:
$data["name"] = "John";
$data["age"] = 31;
$data["city"] = "New York";
2- Encode the array and add it to the database (you can store it as text)
$encodedData = json_encode($data);
3- If you want to add nested json data just make your array nested array.
4- When you restore the data just use json_decode to decode it
Just add this to your Model.
protected $casts = [
'data' => 'object'
];
Then you can get in your view like this:
{{ $data->data->name }}

Trying to use exclude_if on Laravel 6

I'm trying to escape a value from a field according to another field, but it never get escaped. Here's a part of my code. However if 'samename' is true or false, 'res_title' never get escaped. It always end up in my database. I've also tried with 'unless_if', but stil got the same result.
return [
'samename' => 'required|boolean',
'res_title' => 'exclude_if:samename,false'
];
So here is how I process the request, I use Postman :
{
"samename": true,
"res_title": "test"
}
Also, here is my controller :
public function store(DmLogRequest $req)
{
$log = new DmLog();
$log->samename = $req->samename;
$log->res_title = $req->res_title;
$log->save();
return response()->json($log);
}

Can't insert data via rest api

I try using rest api in codeigniter to insert data.
I try this
public function sensor_post(){
$data = array(
'sensor_id' => $this->input->post('sensor_id'),
'value' => $this->input->post('value'));
$insert = $this->db->insert('measurement', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
And call
http://localhost/rest_iot/index.php/iot/sensor?sensor_id=1&value=37
I try this in post man and I get error like this. I think I've fill the value, why this is happend?
<h1>A Database Error Occurred</h1>
<p>Error Number: 1048</p>
<p>Column 'sensor_id' cannot be null</p>
<p>INSERT INTO `measurement` (`sensor_id`, `value`) VALUES (NULL, NULL)</p>
<p>Filename: C:/xampp/htdocs/rest_iot/system/database/DB_driver.php</p>
<p>Line Number: 691</p>
If you are sending the data within the URL, you are sending it via GET. However your code is trying to receive data sent via POST.
I presume in codeigniter you can simply write the code as follows to receive it as GET:
'sensor_id' => $this->input->get('sensor_id'),
'value' => $this->input->get('value')
Either you are sending data via GET or POST ? Assuming that $this->post('sensor_id') you are looking for POST but sending via GET sensor_id=1&value=37.
Send data via POST method or... retrieve via GET
You are missing input in your post fields.
public function sensor_post()
{
$data = array(
'sensor_id' => $this->input->post('sensor_id'),
'value' => $this->input->post('value')
);
$insert = $this->db->insert('measurement', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
This will work for you.

Laravel - Creating an object from a JSON array to save it in a SQL database

What I am trying to do is to send a JSON array (that was gotten from Guzzle) to my SQL database. I have gotten to the point where I am able to get the response and display the gotten JSON array on a webpage. The array is defined as the $data variable. The $data variable gets decoded using this:
$data = json_decode($response->getBody()->getContents());
This is able to get the JSON and decode it with no problem. The part I am stuck on is taking the $data variable, processing it and sending it to my database. From what I understand is that you are required to convert the JSON into an array and then send it to the database.
The JSON format is like this:
[{
"INTLDES": "2017-042Z",
"NORAD_CAT_ID": "42848",
"OBJECT_TYPE": "TBA",
"SATNAME": "OBJECT Z",
"COUNTRY": "TBD",
"LAUNCH": "2017-07-14",
"SITE": "TTMTR",
"DECAY": null,
"PERIOD": "96.52",
"INCLINATION": "97.61",
"APOGEE": "597",
"PERIGEE": "586",
"COMMENT": null,
"COMMENTCODE": null,
"RCSVALUE": "0",
"RCS_SIZE": null,
"FILE": "6242",
"LAUNCH_YEAR": "2017",
"LAUNCH_NUM": "42",
"LAUNCH_PIECE": "Z",
"CURRENT": "Y",
"OBJECT_NAME": "OBJECT Z",
"OBJECT_ID": "2017-042Z",
"OBJECT_NUMBER": "42848"
}]
My Satellite Model goes like this:
protected $fillable = [
'intldes',
'norad_cat_id',
'object_type',
'satname',
'country',
'launch',
'site',
'decay',
'period',
'inclination',
'apogee',
'perigee',
'comment',
'commentcode',
'rcsvalue',
'rcs_size',
'file',
'launch_year',
'launch_num',
'launch_piece',
'current',
'object_name',
'object_id',
'object_number'
];
My migrations file:
Schema::create('satellites', function (Blueprint $table) {
$table->increments('id');
$table->string('intldes');
$table->string('norad_cat_id');
$table->string('object_type');
$table->string('satname');
$table->string('country');
$table->string('launch')->nullable();
$table->string('site')->nullable();
$table->string('decay')->nullable();
$table->string('period')->nullable();
$table->string('inclination')->nullable();
$table->string('apogee')->nullable();
$table->string('perigee')->nullable();
$table->string('comment')->nullable();
$table->string('commentcode')->nullable();
$table->string('rcsvalue')->nullable();
$table->string('rcs_size')->nullable();
$table->string('file')->nullable();
$table->string('launch_year')->nullable();
$table->string('launch_num')->nullable();
$table->string('launch_piece')->nullable();
$table->string('current')->nullable();
$table->string('object_name');
$table->string('object_id');
$table->string('object_number');
$table->timestamps();
});
I tried making an $object array, which did not work.
TL;DR: I want to take the $data variable, which contains the decoded JSON and create something that allows it to get saved into my 'satellites' SQL database.
EDIT: Here is the full Satellite controller:
public function displayer(){
$api = new Client([
'base_uri' => 'https://www.space-track.org',
'cookies' => true,
]); $api->post('ajaxauth/login', [
'form_params' => [
'identity' => '#',
'password' => '#',
],
]);
$response = $api->get('basicspacedata/query/class/satcat/orderby/INTLDES%20desc/limit/5/metadata/false');
$data = json_decode($response->getBody()->getContents(), true);
$data = array_change_key_case($data, CASE_LOWER);
$model = Satellite::create($data);
dd($data);
}
It looks like your JSON key names match up nicely with your model attributes, with the exception of being capitalised.
Try mapping the data keys to lowercase and then creating your model instance.
Per #OmisakinOluwatobi suggestion, you can use pass true to json_decode to retrieve the data as an array.
Edit - I missed that your response data was an array of objects. The following update will iterate over the response data and create a new Satellite for each.
// Retrieve data from response
$data = json_decode($response->getBody()->getContents(), true);
// Iterate over response data
foreach ($data as $attributes) {
// Change attribute keys to lowercase
$attributes = array_change_key_case($attributes, CASE_LOWER);
// Create satellite model
Satellite::create($attributes);
}
It is actually as simple as $encoded = json_encode($request->your_array);. This $encoded will now be "savable" to sql database. When you later access the encoded data, you can use a JSON parser to convert back to a json array. Example using jQuery var your_array = $.parseJSON($response.body);

How to insert an object into MongoDB document using Laravel 4

I am a newbie in Laravel MongoDB I would like to mention a problem here, outline of my Mongo document should be like
{
_id:****,
subscriptions: [{list_id: "14Q3"},
{list_id: "153"}],
offers: [ { targetURL: "www.qwerty.com", title: "25% discount" },
{ targetURL: "www.abcd.com", title: "55% discount" } ],
}
I have used the following code to insert a list id (was successful).
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array('list_id' => $subscriber->list1_id),
));
But when I try to push another list_id as next object it is showing error. I used the following code for pushing
DB::connection('mongodb')->collection('subscribers')
->push('subscriptions', array('list_id' => $subscriber->list1_id));
I don't know whether my code is right or wrong. I need to store the data as the outline given above. This is My actual problem. Please correct me....
My controller is is given below, I create new collection for each subscriber. Problem is second 'if' statement
public function store() {
$newsubscriber = Input::json();
//DB::connection('mongodb')->collection($newsubscriber->get('device_id'))->delete();
$result = Subscriber::where('list1_id',$newsubscriber->get('list_id'))->where('device_id',$newsubscriber->get('device_id'))->get();
if (!$result->isEmpty()) {
return "You are already a subscriber of this List";
}
else{
$result1 = Subscriber::where('device_id',$newsubscriber->get('device_id'))->get();
$subscriber = new Subscriber();
$subscriber->list1_id = $newsubscriber->get('list_id');
$subscriber->device_id = $newsubscriber->get('device_id');
$subscriber->subtype = 1;
$subscriber->save();
if (!$result1->isEmpty()) {
DB::connection('mongodb')->collection($subscriber->device_id)->push('subscriptions', array('list_id' => $subscriber->list1_id));
return "Subscribed successfully 1";
}
else{
DB::connection('mongodb')->collection($subscriber->device_id)->insert(array('_id' => $subscriber->device_id,'subscriptions' => array('list_id' => $subscriber->list1_id),
));
return "Subscribed successfully 2";
}
}
}
First i have used following API
curl -H "Content-Type: application/json" -d '{"list_id":"2","device_id":"987654321"}' http://localhost/lemmeknw/public/index.php/api/v1/subscribe
This returned "Subscribed successfully 2"
but when I used API for second time
curl -H "Content-Type: application/json" -d '{"list_id":"1","device_id":"987654321"}' http://localhost/lemmeknw/public/index.php/api/v1/subscribe
There was error "Something went wrong"
I don't know much about Laravel, but what I'm seeing here:
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array('list_id' => $subscriber->list1_id),
));
Looks like you are creating subscriptions as an object {list_id: <subscriber-list1_id>} instead of an array of one object [{list_id: <subscriber-list1_id>}]. So when you try to use the push operation
DB::connection('mongodb')->collection('subscribers')
->push('subscriptions', array('list_id' => $subscriber->list1_id));
that is an attempt to push to an object, not an array. My guess is that you will need to modify your insert to be
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array(array('list_id' => $subscriber->list1_id)),
));

Categories