I have issue in handling json multiple data. I am not getting multiple data and if I use "array" then also it creates single record with null values in database.
The Backend code for saving data
{
$pickup = new PickupData();
$pickup->pickup_person = $request->pickup_person;
$pickup->office_city = $request->office_city;
$pickup->office_state = $request->office_state;
$pickup->office_pincode = $request->office_pincode;
$pickup->pickup_email = $request->pickup_email;
$pickup->preferred_start_time = $request->preferred_start_time;
$pickup->preferred_end_time = $request->preferred_end_time;
$pickup->mobile = $request->mobile;
$pickup_date = Carbon::parse($request->pickup_date)->format('d-m-Y');
$pickup->pickup_date = $pickup_date;
$saved = $pickup->save();
}
I need response like and it should be saved into database
[
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
},
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
}
]
create resource sth like this
php artisan make:resource PickupResourceCollection
create another resource sth like
php artisan make:resource PickupResource
in your index method of PickupController do sth like this
use use App\Http\Resources\PickupResourceCollection;
...
public function index()
{
$pickups = Pickup::all();
return response()->json(new PickupResourceCollection($pickups),200);
}
...
in PickupResourceCollection do sth like this
....
public function toArray($request)
{
return [
'data' => $this->collection->transform(function ($pickups) {
return new PickupResource($pickups);
})
];
}
....
in PickupResource do sth like this
....
public function toArray($request)
{
return [
"pickup_person" =>$this->pickup_person,
"city" =>$this->city,
"office_address" =>$this->office_address,
"office_city" =>$this->office_city,
"office_state" =>$this->office_state,
"office_pincode" =>$this->office_pincode,
"pickup_email" =>$this->pickup_email,
"preferred_start_time"=>$this->preferred_start_time,
"preferred_end_time" =>$this->preferred_end_time,
"mobile" =>$this->mobile,
"pickup_date" =>"$this->pickup_date
];
}
....
thats it :)
Yes you can save by as an array.
$pickup = PickupData::create($request->all()) // to save all request data
$pickup = PickupData::create($request->except(['var1', 'var2'])) // to save all request data except var1 & var2
$pickup will return only newly inserted row.
$pickupDetails = [
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
},
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
}
];
$pickupDetails = $request->all();
foreach($pickupDetails as $pickup){
Pickup::create($pickup);
}
return response()->json("success",200);
if it helps you upvote me :)
Related
I am not receiving formdata in the Api endpoint which is being sent by fetch and PUT method.
I used the POST method and it worked out which i think is not recommended for updating.
I have react running on localhost:3000 and the laravel-API running on localhost:5000.
This is the route in API
Route::put('updateSlide/{id}', 'SlidesController#updateSlide');
This is what is in the controller
public function updateImage(Request $request, int $id)
{
$image = $this->slideRepo->findSlideById($id)->image;
if ($image) {
$result = Storage::disk('ucmp')->delete($image);
}
if ($request->hasFile('image') && $request->file('image') instanceof UploadedFile) {
return $this->slideRepo->saveCover($request->file('image'));
} // return response()->json($data);
// data is an array (note)
return null;
}
public function updateSlide(Request $request, int $id)
{
$imageUrl=$this->updateImage($request, $id);
return response()->json($this->slideRepo->updateSlide([
'caption' => $request['caption'],
'image' => $imageUrl,
'url' => $request['url']
],$id));
}
This is the function sending to fetch
export const updateSlideApi = (token, _slide, id) => {
return {
url: `${BASE_URL}/api/updateSlide/${id}`,
opt: API.requestOptions("PUT",token,null,{ body: _slide }, true)
};
};
In my header i do not have the content-type.
I expect json data from the laravel API function but am having an error, " Can only throw objects"
PHP does not parse the body of a PUT request.
Use POST and add parameter _method with value PUT.
PHP put has given me tough time, use this function will save your time parsing it else method:
function parsePutRequest()
{
// Fetch content and determine boundary
$raw_data = file_get_contents('php://input');
$boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));
// Fetch each part
$parts = array_slice(explode($boundary, $raw_data), 1);
$data = array();
foreach ($parts as $part) {
// If this is the last part, break
if ($part == "--\r\n") break;
// Separate content from headers
$part = ltrim($part, "\r\n");
list($raw_headers, $body) = explode("\r\n\r\n", $part, 2);
// Parse the headers list
$raw_headers = explode("\r\n", $raw_headers);
$headers = array();
foreach ($raw_headers as $header) {
list($name, $value) = explode(':', $header);
$headers[strtolower($name)] = ltrim($value, ' ');
}
// Parse the Content-Disposition to get the field name, etc.
if (isset($headers['content-disposition'])) {
$filename = null;
preg_match(
'/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/',
$headers['content-disposition'],
$matches
);
list(, $type, $name) = $matches;
isset($matches[4]) and $filename = $matches[4];
// handle your fields here
switch ($name) {
// this is a file upload
case 'userfile':
file_put_contents($filename, $body);
break;
// default for all other files is to populate $data
default:
$data[$name] = substr($body, 0, strlen($body) - 2);
break;
}
}
}
return $data;
}
I need to store interest_amount which is computed using get_Attribute function however now I need to insert it into table.
I have used static::saving function to compute interest_amount I don't know how to call it using $data in controller
Loan.php
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $fillable = [
'amount',
'interest',
'status',
'duration',
'member_id',
'loan_type_id',
'interest_type_id',
'loan_payment_type_id'
];
protected $appends = 'interest_amount';
public function getInterestAmountAttribute()
{
return ($this->amount)/100 * $this->interest;
}
public function member()
{
return $this->belongsTo(Member::class,'member_id','id');
}
protected static function boot()
{
parent::boot();
static::saving(function($model) {
$model->interest_amount = ($model->amount/100 ) * $model->interest;
});
}
}
LoanController.php
$data['amount'] = $request->amount;
$data['interest'] = $request->interest;
$data['interest_amount'] = $interest_amount;
$data['duration'] = $request->duration;
$data['status']= $request->status;
$data['member_id'] = $request->name;
$data['loan_type_id']= $request->loan_type;
$data['interest_type_id']= $request->interest_type;
$data['loan_payment_type_id']= $request->payment;
if(DB::table('loans')->insert($data)){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
I initially didn't have interest_amount column but I added it later. I don't know how to call the saving function with the approach I have used in my controller.
Model events will not fire when you use the query builder to insert data into your tables.
You have to use the Model to save the data, something like this:
If your model attributes are mass assignable:
if((new Loan($data))->save()){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
otherwise:
$loan = new Loan;
$loan->amount = $request->amount;
$loan->interest = $request->interest;
$loan->interest_amount = $interest_amount;
$loan->duration = $request->duration;
$loan->status = $request->status;
$loan->member_id = $request->name;
$loan->loan_type_id = $request->loan_type;
$loan->interest_type_id = $request->interest_type;
$loan->loan_payment_type_id = $request->payment;
if($loan->save()){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
I'am trying to fetch a session variable if the user is a guest. The variable is called "cart" and is set like this:
$product = new Collection((object) [
'product_id' => $request->pId,
'amount' => $request->amount,
'variations' => $variations
]);
Session::push('cart', $product);
Then I later fetch it:
if(Auth::check()){
$cartProducts = ShoppingCartItem::where('user_id', '=', Auth::user()->id)->get();
}else{
$cartProducts = Session::get('cart');
}
foreach($cartProducts as $product){
dd($product);
$totalAmount += $product->amount;
$totalPrice += (PriceHelper::getProductPrice($product->product->id, $product->amount));
}
The problem here is that dd($product) still outputs an array (the session variable array I assume) which means that for example $product->amount does not exist.
This is the output from dd($product):
You can either access the values using get():
foreach ($cartProducts as $product) {
$totalAmount += $product->get('amount');
$totalPrice += PriceHelper::getProductPrice($product->get('product_id'), $product->get('amount'));
}
or as an array:
foreach ($cartProducts as $product) {
$totalAmount += $product['amount'];
$totalPrice += PriceHelper::getProductPrice($product['product_id'], $product['amount']);
}
or you could use sum() on the collection instead of using foreach:
$cartProducts = collect(Session::get('cart'));
$totalAmount = $cartProducts->sum('amount');
$totalPrice = $cartProducts->sum(function ($product) {
return PriceHelper::getProductPrice($product['product_id'], $product['amount']);
});
Edit
For a quick fix if you need $product to be an object you could do something like:
$cartProducts = collect(Session::get('cart'))->map(function ($item) {
return (object)$item->toArray();
});
Hope this helps!
Hello i am having slight trouble with arrays in my application. I have a table in my database called "contacts" inside that table i have a column "info" of datatype 'TEXT' where i store a json encoded array. This is my function:
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$contact = new Contacts;
$contact->type = $request->type;
$contact->name = str_replace(' ', ' ', $request->type == 'person' ? $request->first_name . ' ' . $request->other_name . ' ' . $request->last_name : $request->description);
$contact->email = $request->email;
$contact->info = json_encode($request->info);
if ($contact->save())
{
return [
'success' => 'Data was saved successfully!'
];
}
}
Now this saves perfectly however the issues is when i retrieving the data from the database it returns that column as a "string" and as such i am unable to access that array from my front-end javascript (i use angular).
I have tried decoding the entire returned result but that did not work, still had the same problem:
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$type = Input::get('type');
$contacts = "";
if (empty($type))
{
$contacts = Contacts::get();
}
elseif ($type == 'persons')
{
$contacts = Contacts::where('type', 'person')->get();
}
elseif ($type == 'companies')
{
$contacts = Contacts::where('type', 'company')->get();
}
return [
'contacts' => json_decode($contacts)
];
}
Use the $casts property on your model:
class Contacts extends Eloquent
{
protected $casts = ['inof' => 'json'];
}
It'll handle all encoding/decoding for you.
$contact->info = $request->info;
I have just stumbled upon very strange behaviour. In my code I am saving new node with some fields. I must say this used to work perfectly well. However now it just stopped working. I use the devel module to print out the content of objects and variables and this is my code:
dsm($node);
node_save($node);
dsm($node);
The first dsm() function displays node object as I created it and as it is supposed to be. The second dsm() function displays entirely correct node object with nid populated, fields content, etc... However, none of the fields is saved in database although there is new record in {node} table. Also, node_save does not generate any kind of error.
Any idea what is happening here?
This is the function storing the node:
function manhattan_incident_save($data) {
if ($data['nid']) {
$node = node_load($data['nid']);
manhattan_compare_changes($node, $data);
}
else {
$node = new stdClass();
$node->type = 'incident';
node_object_prepare($node);
$node->title = manhattan_create_incident_id();
$node->language = LANGUAGE_NONE;
}
$node->field_incident_popis[$node->language][0]['value'] = $data['field_incident_popis'];
$node->field_incident_popis[$node->language][0]['safe_value'] = check_plain($data['field_incident_popis']);
$node->field_incident_agent[$node->language][0]['uid'] = isset($data['field_incident_agent'])?intval($data['field_incident_agent']):NULL;
$node->field_incident_zdroj[$node->language][0]['tid'] = intval($data['field_incident_zdroj']);
$node->og_group_ref[$node->language][0]['target_id'] = $data['field_incident_oblast']?intval($data['field_incident_oblast']):variable_get('manhattan_public_form_default_area_nid', NULL);
$node->field_incident_riesitel[$node->language][0]['uid'] = isset($data['field_incident_riesitel'])?intval($data['field_incident_riesitel']):NULL;
$node->field_incident_typ[$node->language][0]['tid'] = intval($data['field_incident_typ']);
$node->field_incident_doplnenie[$node->language][0]['nid'] = intval($data['field_incident_doplnenie']);
$node->field_incident_sposob_kontaktu[$node->language][0]['value'] = $data['field_incident_sposob_kontaktu'];
$node->field_incident_dovod_vzniku[$node->language][0]['tid'] = intval($data['field_incident_dovod_vzniku']);
if ($data['field_incident_suvisiaci_zaznam']) {
foreach ($data['field_incident_suvisiaci_zaznam'] as $file) {
$result = manhattan_save_files($file);
if ($result) {
$node->field_incident_suvisiaci_zaznam[$node->language][] = array('nid' => $result);
}
}
}
// now create/save the customer
if (function_exists('customer_customer_save')) {
$customer = $data;
$customer['nid'] = $data['field_incident_customer'];
$result = customer_customer_save($customer);
if ($result) {
watchdog('upvs', $result['message'], array(), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('There was a problem with saving customer %nid'), array('%nid' => $data['nid']), WATCHDOG_ERROR);
}
}
// now we store nid of saved customer to the node object
$node->field_incident_customer[$node->language][0]['nid'] = $result['nid'];
dsm($node);
node_save($node);
dsm($node);
if ($data['nid']) {
watchdog('upvs', t('Incident number %title has been succesfully saved.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('Incident number %title has been succesfully created.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
return $node;
}