How to make array with => php (Laravel) - php

I have my shopping cart with main logic in custom class:
public $items = NULL;
public $totalQty = 0;
public $totalPrice = 0;
public function __construct($oldCart){
if($oldCart){
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function add($item, $id){
$storedItem = [
'qty' => 0,
'id' => $item->id,
'prod_url' => $item->url,
'code_cat' => $item->category->code,
'url_cat' => $item->category->url,
'name' => $item->name,
'cost' => $item->price,
'price' => $item->price,
'img' => $item->cardImage->path
];
if($this->items){
if(array_key_exists($id, $this->items)){
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['cost'] = $item->price * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->price;
}
To place order I serialize this array and store in DB.
public function new_order_place(Request $request){
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
$order = new Order();
$order->cart = serialize($cart);
$order->name = $request->input('name')?$request->input('name'):Auth::user()->name;
$order->email = $request->input('e-mail') ? $request->input('e-mail'):Auth::user()->email;
$order->phone = $request->input('phone')?$request->input('phone'):(Auth::user()->phone?Auth::user()->phone:$this->validate($request, ['phone' => 'required']));
$order->address = $request->input('address');
Auth::check()?Auth::user()->orders()->save($order):$order->save();
Session::forget('cart');
return redirect()->route('index');
}
Array looks like:
__PHP_Incomplete_Class Object
(
[__PHP_Incomplete_Class_Name] => App\Classes\Cart
[items] => Array
(
[4] => Array
(
[qty] => 1
[id] => 4
[prod_url] => gorenje_g_5111_wf
[code_cat] => large-home-appliances
[url_cat] => cookers
[name] => Плита газовая GORENJE G 5111 WF
[cost] => 490
[price] => 490
[img] => img_16.jpg
)
)
[totalQty] => 1
[totalPrice] => 490
)
But also I have a modal with a Buy Now button where a user can buy a specific product without adding it to the cart. I am trying to create the same array because I cannot display orders in the user panel due to the different array structure.
public function modal_order_place(Request $request){
$selprod['items'] = array(
$request->id => array(
'name' => $request->name,
'qty' => $request->qty,
'code' => $request->code,
'img' => $request->img,
'totalPrice' => $request->totalPrice
)
);
$order = new Order();
$order->cart = serialize($selprod);
$order->name = $request->username;
$order->email = $request->email;
$order->phone = $request->phone;
Auth::check()?Auth::user()->orders()->save($order):$order->save();
return response()->json([
'notif_text' => 'Your order has been accepted for processing! Expect a call!'
]);
}
Laravel swears:
Attempting to get the "items" property of a non-object
If I delete the product added through the modal window, then everything is already working. The problem is in the array.
How is it possible to create the same array?

You need another level of nesting.
$selprod['items'] = array(
$request->id => array(
'id' => $request->id,
'name' => $request->name,
'code' => $request->code,
'img' => $request->img,
)
);

Found a solution. To fix this problem, you need to convert it to an object before serializing our array. From my code:
public function modal_order_place(Request $request){
$selprod['items'] = array(
$request->id => array(
'name' => $request->name,
'qty' => $request->qty,
'code' => $request->code,
'img' => $request->img,
'totalPrice' => $request->totalPrice
)
);
$object = (object)$selprod;//This line will convert our array to an object
$order = new Order();
$order->cart = serialize($object);//Here we are already serializing our object, not an array
$order->name = $request->username;
$order->email = $request->email;
$order->phone = $request->phone;
Auth::check()?Auth::user()->orders()->save($order):$order->save();
return response()->json([
'notif_text' => 'Your order has been accepted for processing! Expect a call!'
]);
}
During deserialization, an array is obtained with the same structure as the basket creates and Laravel no longer swears:
stdClass Object
(
[items] => Array
(
[3] => Array
(
[name] => name
[qty] => 1
[img] => img_10.jpg
[cost] => 380
)
)
)

Related

how to condition same time product to insert and update in laravel

I am tring Order update.I need to update multi product in different row. when I update the product then it only updated created fields. i want to update current row and then new product insert in different row.
$product_id = $request->product_id;
$seller_id = Auth::user()->id;
$price = $request->product_price;
$quantity = $request->product_qty;
$payment_status = $request->payment_status;
$delivery_status = $request->delivery_status;
$shipping_type = "home_delivery";
$shipping_charge = $request->shipping_cost;
$user = Address::all()->where('user_id', $request->user_id)->first();
$cname= DB::table('users')->where('id', $user->user_id)->value('name');
$shipping_address = [
'user_id'=>$request->user_id,
'name'=> $request->name,
'phone'=>$request->phone,
'email'=>$user->email,
'city'=>$user->city,
'postal_code'=>$user->postal_code,
'country'=>$user->country,
'address'=>$request->address,
];
$order_id=$request->id;
$order = Order::findOrFail($order_id)->update([
'seller_id' => Auth::user()->id,
'shipping_address' => json_encode($shipping_address),
'payment_status' => $request->payment_status,
'payment_type' => $request->payment_option,
'payment_details' => $request->payment_option,
'coupon_discount' => $request->coupon_discount,
'round_amount' => $request->round_discount,
'grand_total' => $request->grand_total,
]);
for($i = 0; $i <= count($request->product_id)-1; $i++){
$data = [
'order_id' => $order_id,
'product_id' => $product_id[$i],
'seller_id' => $seller_id,
'price' => $price[$i],
'quantity' => $quantity[$i],
'payment_status' => $payment_status,
'delivery_status' => $delivery_status,
'shipping_type' => $shipping_type,
'shipping_cost' => $shipping_charge,
];
if(!empty(OrderDetail::where('order_id', $order_id))){
OrderDetail::where('order_id', $order_id)->update($data);
}
else{
Orderdetail::insert($data);
}
$product_stock_info = ProductStock::where('product_id', $product_id[$i])->first();
// dd($product_id[$i]);
$stock = $product_stock_info->qty;
$updateStock = $stock - $quantity[$i];
$product_stock_info->qty = $updateStock;
$product_stock_info->save();
}
my problem is here
if(!empty(OrderDetail::where('order_id', $order_id))){
OrderDetail::where('order_id', $order_id)->update($data);
} else {
Orderdetail::insert($data);
}
You can use updateOrCreate method .
the updateOrCreate method persists the model, so there's no need to manually call the save method
$flight = Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
as like
$whereData = [
'order_id' => $order_id
];
OrderDetail::updateOrCreate($whereData ,$data);

how to store simply multi array in session laravel 5.6

i store one array in to session('cart') last click [add to cart] , when i add another array in session('cart'), but it store one array then session can not save both.
help me !
public function addtocart(Request $req,$id){
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$req->session()->put('cart',$cart);
$a = session()->get('cart');
}
change this
$req->session()->put('cart',$cart);
$a = session()->get('cart');
dd($a);
to this:
$cartvalues[] = $cart;
$req->session()->put('cart',$cartvalues);
$a = session('cart');
dd($a);
because you keep overwriting the previous value inside the session cart
Here you are overwriting cart variable in session every time you add a new item. So store cart items as an array and add item to array. Code should be:
public function addtocart(Request $req, $id) {
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$cartItems = session()->get('cart');
if (empty($cartItems)) {
$cartItems = [];
}
$cartItems[] = $cart;
$req->session()->put('cart', $cartItems);
return view($cartItems);
}
Here is the simple example to update your cart in your case
`
public function addtocart(Request $req,$id){
//return redirect('Resouce/product');
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
if($req->session()->has('cart')){
$oldCart = $req->session()->get('cart');
$newCart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => array_merge($item,$oldCart['item'])
];
$req->session()->put('cart',$newCart);
}
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$req->session()->put('cart',$cart);
$a = session()->get('cart');
dd($a);
}`

Laravel Table Filter

So I have website based on Laravel framework. I have table and the filter for table to filter the items - http://prntscr.com/ccht0f.
When I filter them by anything all works good, but when I change the page filtering disapers from session. http://prntscr.com/cchutt - http://prntscr.com/cchuyo. Looks like pagination destroys all sessions.
My code:
public function filters(Request $request)
{
$filter_item_acquisition_forms = [null];
$filter_collections = [null];
$filter_origin_dates = [null];
$order_by = request()->query('order_by', 'id');
$dir = request()->query('dir', 'desc');
$storage_items = StorageItem::with(
'authorClassification',
'placeClassification',
'classificationValueOrigin',
'classificationValueOriginDate',
'classificationValueItemAcquisitionForm',
'classificationValueCollection',
'classificationValuesMaterials',
'classificationValuesTechnique',
'employeeClassificationsRestorers',
'userLastUpdatedBy.employeeClassification',
'userResponsibleUser.employeeClassification',
'attachments'
);
$storage_items = $storage_items->id($request->filter_id)
->acceptanceId($request->filter_acceptance_id)
->acceptanceNumber($request->filter_acceptance_number)
->acceptanceDate($request->filter_acceptance_date)
->mainInventoryNumber($request->filter_main_inventory_number_from, $request->filter_main_inventory_number_to)
->scientificInventoryNumber($request->filter_scientific_inventory_number)
->imageInventoryNumber($request->filter_image_inventory_number)
->itemCosts($request->filter_item_costs_from, $request->filter_item_costs_to)
->originDate($request->filter_origin_date)
->updatedAt($request->filter_updated_at_from, $request->filter_updated_at_to)
->addingDate($request->filter_added_from, $request->filter_added_to)
->itemAcquisitionForm($request->filter_item_acquisition_form)
->collection($request->filter_collection)
->employee($request->filter_employee)
->isInExposition($request->filter_is_in_exposition)
->isRestored($request->filter_is_restored)
->haveAttachments($request->filter_have_attachments)
->haveNotCosts($request->filter_have_not_costs)
->searchInField($request->filter_search_in_field, $request->filter_word_or_phrase);
$storage_items = $storage_items->orderBy($order_by, $dir)->paginate(20);
foreach ($storage_items as $storage_item) {
if ($storage_item->classificationValueItemAcquisitionForm != null) {
$filter_item_acquisition_forms[$storage_item->classificationValueItemAcquisitionForm->id] = $storage_item->classificationValueItemAcquisitionForm->value;
}
if ($storage_item->classificationValueCollection != null) {
$filter_collections[$storage_item->classificationValueCollection->id] = $storage_item->classificationValueCollection->value;
}
if (!is_null($storage_item->classificationValueOriginDate)) {
$filter_origin_date[$storage_item->classificationValueOriginDate->id] = $storage_item->classificationValueOriginDate->value;
}
}
$request->flash();
return view('panel.storage_items.filters')->with([
'storage_items' => $storage_items,
'current_order_query' => compact('order_by', 'dir'),
'employees' => [null] + EmployeeClassification::lists('employee', 'id')->toArray(),
'filter_what_to_look_for' => [
'storage-items' => trans('fields.storage_items'),
'storage-item-acceptances' => trans('fields.storage_items_acceptances'),
'archive-objects' => trans('fields.archive_objects'),
'archive-documents' => trans('fields.archive_documents'),
'archive-docs-acceptance-acts' => trans('fields.archive_documents_acceptance_acts')
],
'filter_item_acquisition_forms' => $filter_item_acquisition_forms,
'filter_collections' => [null] + Classification::findOrFail(2)->classificationValues()->lists('value', 'id')->toArray(),
//'filter_collections' => $filter_collections,
'filter_origin_dates' => $filter_origin_dates,
'filter_search_in_field' => [
trans('fields.storage_items') => [
'item_name' => trans('fields.item_name'),
'author' => trans('fields.author'),
'about_the_author' => trans('fields.about_author'),
'item_description' => trans('fields.item_description'),
'content_description' => trans('fields.content_description'),
'item_history' => trans('fields.item_history'),
'branding_notes' => trans('fields.branding_notes'),
'damage_characteristics' => trans('fields.damage_characteristics'),
'published' => trans('fields.published'),
'exhibited' => trans('fields.exhibited'),
'inquiries' => trans('fields.inquiries')
],
trans_choice('fields.attachments', 0) => [
'attachment_name' => trans('fields.name'),
'attachment_description' => trans('fields.description')
]
]
]);
}
So I fixed it myself.
Solution:
I got the collection ID from request and stored it in variable.
$filter_collection = $request->filter_collection;
Passed variable to the view
->with('filter_collection', $filter_collection)
And changed my pagination to pass collection ID to next page
{{ $storage_items->appends(['filter_collection' => $filter_collection])->links() }}

mongodb + yii2: How can i push an array/object to mongodb?

I am playing around with yii2 and mongodb and i am stuck at a one point. I have created the CRUD functionality using mongodb GII. Now i am making modification to put the objects of array in my database record.
On creation of a customer i create an object of mileage and push it like this.
$model = new Customer();
if ($model->load(Yii::$app->request->post())) {
$mileage = new mileage(2, 'British Airways', 'Usman', 10000);
$model->mileage = array($mileage);
$model->save();
return $this->redirect(['view', 'id' => (string) $model->_id]);
}
mileage.php
class Mileage {
public $_id;
public $sm_order_id;
public $program;
public $customer;
public $miles;
public function __construct($sm_order_id, $program, $customer, $miles) {
$this->_id = new \MongoId();
$this->sm_order_id = $sm_order_id;
$this->program = $program;
$this->customer = $customer;
$this->miles = $miles;
}
}
and i get the data in the following format in database:
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002c',
)),
'name' => 'Alan',
'email' => 'alan#abc.com',
'address' => 'New York',
'mileage' =>
array (
0 =>
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002b',
)),
'sm_order_id' => 2,
'program' => 'British Airways',
'customer' => 'Wake',
'miles' => 10000,
),
),
)
Now i want a mechanism so i can add more array/objects in mileage node. I have searched a lot but didn't find anything. Same format of the database is mentioned below:
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002c',
)),
'name' => 'Alan',
'email' => 'alan#abc.com',
'address' => 'New York',
'mileage' =>
array (
0 =>
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002b',
)),
'sm_order_id' => 2,
'program' => 'British Airways',
'customer' => 'Wake',
'miles' => 5000,
),
1 =>
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002c',
)),
'sm_order_id' => 7,
'program' => 'Qatar Airways',
'customer' => 'Tony',
'miles' => 2500,
),
),
2 =>
array (
.........
.........
),
)
Ok I have found out the solution long time ago and i thought i should share it here. So i am pushing the 1st object in mileage node like that:
$model = Customer::findOne($customerId);
if ($model->load(Yii::$app->request->post())) {
$mileage = new mileage(2, 'British Airways', 'Usman', 10000);
$model->mileage = array($mileage);
$model->save();
return $this->redirect(['view', 'id' => (string) $model->_id]);
}
So to add another object in mileage node, what we need to do is we need to get the customer object from database and we have to check if there is already an object added in the mileage node and then i have to get that object and push the newly created mileage array/object in it. modified code is below:
$model = Customer::findOne($customerId);
if ($model->load(Yii::$app->request->post())) {
$mileage = new mileage(2, 'British Airways', 'Kamran', 9000);
if (empty($model->mileage) || count($model->mileage) == 0) {
$model->mileage = array($mileage);
} else {
$allUsedMiles = $model->mileage;
array_push($allUsedMiles, $mileage);
$model->mileage = $allUsedMiles;
}
$model->save();
return $this->redirect(['view', 'id' => (string) $model->_id]);
}
I hope this will help someone in the future ;)
Thanks,

Unable to insert data into database using codeigniter

I want to insert data into my database. I am using codeigniter framework to build my app.
When I click on submit button,It don't give any error just reload the same page and data in not inserted in database.
Following my code to insert data into database -
public function addSale($saleDetails = array(), $items = array(), $warehouse_id)
{
foreach($items as $data){
$product_id = $data['product_id'];
$product_quantity = $data['quantity'];
$this->updateProductQuantity($product_id, $warehouse_id, $product_quantity);
}
// sale data
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
if($this->db->insert('sales', $saleData)) {
$sale_id = $this->db->insert_id();
$addOn = array('sale_id' => $sale_id);
end($addOn);
foreach ( $items as &$var ) {
$var = array_merge($addOn, $var);
}
if($this->db->insert_batch('sale_items', $items)) {
return true;
}
}
return false;
}
Based on https://ellislab.com/codeigniter/user-guide/database/examples.html , it seems to me, that you are missing a line -> $this->db->insert('sales', $saleData); . You do have it inside an if statement, but if statement will not execute it as a code, but check if it returns true.
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
$this->db->insert('sales', $saleData);
This should work. You can also check if it succeeds like this ->
return ($this->db->affected_rows() != 1) ? false : true;

Categories