how to update multiple json encode data in single column field? - laravel-5.8

array:2 [▼
0 => "iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AABNq0lEQVR42u3dCZwcVZ3A8Uq6uqu6uqYnx2RykBBCEmIgQCAJSTiUQ1cQEBDUFVRcQVhALg9UUIH1xAVcXHQBBUUEFhREBXHF9eKW3RUQBQVclMso ▶"
1 => "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAACxKgAAsSoBYacs7wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAACAASURBVHic7Z13 ▶"
]
code:
$multi_image = $request->file('multi_image');
if ($multi_image == '')
{
$data[] = 'null';
}
else
{
$file = $request->file('multi_image');
for($i = 0 ; $i< count($file); $i++)
{
$data[]= base64_encode(file_get_contents($file[$i]));
}
}
$sort = $request->input('category_id');
$order = Category::where('id','=',$sort)->first();
$item = new Item();
$item->admin_id = Auth::user()->id;
$item->category_id = $request->input('category_id');
$item->category_sort_order = $order->sort_order;
$item->name = $request->input('name');
$item->description = $request->input('description');
$item->image = $image;
$item->multi_image = json_encode($data);
// $item->currency = '₹';
$item->price = $request->input('price');

Related

How to use save() method inside a loop in laravel

My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.

Loop through a string array in laravel

I'm trying to loop through a a string and get array of records where the service status is equals to complete or cancelled. I'm having an issue of get all the records instead it response with the last record from the list.
My Controller:
$id = $request->user_id;
$history = bookings::select('*')->whereIn('service_status', ['complete', 'cancelled'])->where(['specialist_id'=>$id])->orderBy('time', 'DESC')->get();
if($history->isempty()){
return response()->json(['statusCode'=>'5', 'statusMessage' => 'Empty Record', 'data' =>[]]);
}else{
for($i = 0; $i < count($history); $i++){
$b_id = $history[$i]->id;
$service = $history[$i]->service;
$time = $history[$i]->time;
$date = $history[$i]->date;
$location = $history[$i]->location;
$payment = $history[$i]->payment_type;
$price = $history[$i]->amount;
$special_request = $history[$i]->special_request;
$s_id = $history[$i]->costumer_id;
}
$user = User::with('profile')->find($s_id);
$data = array(['id'=>$b_id, 'date'=>$date, 'name'=>$user->name." ".$user->profile->lastname, 'speccial_request'=>$special_request, 'item'=>$service, 'time'=>$time." - 1 hour", 'location'=>$location, 'total'=>"$price"]);
return response()->json(['statusCode'=>'0', 'statusMessage' => 'Successful','data' => $data], 200);
}
My response is as follows:
{
"statusCode": "0",
"statusMessage": "Successful",
"data": [
{
"id": 5,
"date": "2020-07-08",
"name": "User1",
"speccial_request": null,
"item": "Service",
"time": "10:00 - 1 hour",
"location": "street, city",
"total": "300"
}
]
}
I want to get all the items from the DB not just one.
You need to create an empty array ($data) and push to that array in each iteration.
Try below code:
$id = $request->user_id;
$history = bookings::select('*')->whereIn('service_status', ['complete', 'cancelled'])->where(['specialist_id'=>$id])->orderBy('time', 'DESC')->get();
if($history->isempty()){
return response()->json(['statusCode'=>'5', 'statusMessage' => 'Empty Record', 'data' =>[]]);
}else{
$data=[];
for($i = 0; $i < count($history); $i++){
$b_id = $history[$i]->id;
$service = $history[$i]->service;
$time = $history[$i]->time;
$date = $history[$i]->date;
$location = $history[$i]->location;
$payment = $history[$i]->payment_type;
$price = $history[$i]->amount;
$special_request = $history[$i]->special_request;
$s_id = $history[$i]->costumer_id;
$user = User::with('profile')->find($s_id);
array_push($data,['id'=>$b_id, 'date'=>$date, 'name'=>$user->name." ".$user->profile->lastname, 'speccial_request'=>$special_request, 'item'=>$service, 'time'=>$time." - 1 hour", 'location'=>$location, 'total'=>"$price"]);
}
return response()->json(['statusCode'=>'0', 'statusMessage' => 'Successful','data' => $data], 200);
}

Paypal displaying 400 error when copoun is applied

I am using paypal integration in my web application everything is working fine . Checkout is working properly but when i apply the coupon then the paypal throws the exception of 400 error. Below is my code
I am using the daryldecode/cart for the checkout. The only problem is when I apply the coupon and move forward towards the paypal
public function paywithPaypal(Request $request)
{
// dd($request->all());
if(Auth::guest()){
if(Session::has('user_id')){
$sessionUserId = Session::get('user_id');
echo $sessionUserId;
}
$checkEmail= User::where('email',$request->billing_email )->first();
if(empty($checkEmail)) {
$user = User::create( [
'first_name' => $request->billing_first_name,
'last_name' => $request->billing_last_name,
'email' => $request->billing_email,
'username' => $request->billing_first_name,
'password' => bcrypt( 123456 ),
'province' => $request->billing_state,
'city' => $request->billing_town,
'address' => $request->billing_address_1,
'role' => 'Member',
] );
$userId = $user->id;
}else{
$userId = $checkEmail->id;
}
}else{
//user login
$sessionUserId = $userId = Auth::user()->id;
}
$items = [];
\Cart::session($sessionUserId)->getContent()->each(function($item) use (&$items)
{
$items[] = $item;
});
$subtotal = \Cart::session($sessionUserId)->getSubTotal();
// dd($subtotal);
$line1 = $request->billing_address_1;
$line2 = $request->billing_address_2;
$fullname = $request->billing_first_name ." ". $request->billing_last_name;
$state = $request->billing_state;
$zip = $request->billing_zip;
$phone = $request->billing_phone;
$email = $request->billing_email;
$city = $request->billing_town;
//invoke new order
$order = new Orders ;
$order->id = $order->generateID('INV');
$saved_order_id = $order->id;
$shippingAddress= Paypalpayment::shippingAddress();
$shippingAddress->setLine1($line1)
->setLine2($line2)
->setCity($city)
->setState($state)
->setPostalCode($zip)
->setCountryCode("US")
->setPhone($phone)
->setRecipientName($fullname);
// ### Payer
// A resource representing a Payer that funds a payment
// Use the List of `FundingInstrument` and the Payment Method
// as 'credit_card'
$payer = Paypalpayment::payer();
$payer->setPaymentMethod("paypal");
$listitem = array();
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$shipping = $request->shipping_fee;
foreach($items as $key=>$item){
$listitem[$key] = Paypalpayment::item();
$listitem[$key]->setName($item->name)
->setCurrency('USD')
->setQuantity($item->quantity)
->setPrice($item->price);
$item_detail = new Order_Item_Details;
$item_detail->order_id = $saved_order_id;
$item_detail->item_id = $item->id;
$item_detail->qty = $item->quantity;
$item_detail->save();
}
$itemList = Paypalpayment::itemList();
$itemList->setItems($listitem)
->setShippingAddress($shippingAddress);
$details = Paypalpayment::details();
$details->setShipping($shipping)
->setHandlingFee($fee)
//total of items prices
->setSubtotal($subtotal);
$grandTotal = $subtotal + $fee + $shipping;
//dd($grandTotal);
//Payment Amount
$amount = Paypalpayment::amount();
$amount->setCurrency("USD")
// the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping).
->setTotal($grandTotal)
->setDetails($details);
//dd($amount);
// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
$transaction = Paypalpayment::transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber($saved_order_id)
->setCustom($request->shipping_service);
// dd($transaction);
// ### Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
$redirectUrls = Paypalpayment::redirectUrls();
$redirectUrls->setReturnUrl(url("/payments/success"))
->setCancelUrl(url("/payments/fails"));
$payment = Paypalpayment::payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$order->status = 1;
$order->user_id = $userId;
$order->total = $grandTotal;
$order->subtotal = $subtotal;
$order->shipping = $shipping;
if($request->coupon_code == ""){
$order->isCoupon = 0;
}
else{
$order->isCoupon = 1;
}
$order->isBillingDetail = 1;
if($request->shipping_first_name <> ""){
$order->isShippingDetail = 1;
}
if($request->has('order_notes')){
$order->notes = $request->order_notes;
}
$order->save();
$order_billing = new Order_Billing_Details;
$order_billing->order_id = $order->id;
$order_billing->first_name = $request->billing_first_name ;
$order_billing->last_name = $request->billing_last_name ;
$order_billing->company = $request->billing_company_name ;
$order_billing->address_line_1 = $line1;
$order_billing->address_line_2 = $line2;
$order_billing->state = $state;
$order_billing->city = $city;
$order_billing->postal_code = $zip;
$order_billing->email = $email;
$order_billing->phone = $phone;
$order_billing->save();
if($request->shipping_first_name <> ""){
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->shipping_first_name ;
$order_shipping->last_name = $request->shipping_last_name ;
$order_shipping->company = $request->shipping_company_name ;
$order_shipping->address_line_1 = $request->shipping_address_1 ;
$order_shipping->address_line_2 = $request->shipping_address_2 ;
$order_shipping->state = $request->shipping_state ;
$order_shipping->city = $request->shipping_town ;
$order_shipping->postal_code = $request->shipping_zip ;
$order_shipping->email = $email ;
$order_shipping->phone = $request->shipping_phone ;
$order_shipping->save();
}
else{
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->billing_first_name ;
$order_shipping->last_name = $request->billing_last_name ;
$order_shipping->company = $request->billing_company_name ;
$order_shipping->address_line_1 = $line1;
$order_shipping->address_line_2 = $line2;
$order_shipping->state = $state;
$order_shipping->city = $city;
$order_shipping->postal_code = $zip;
$order_shipping->email = $email;
$order_shipping->phone = $phone;
$order_shipping->save();
}
try {
// ### Create Payment
// Create a payment by posting to the APIService
// using a valid ApiContext
// The return object contains the status;
//dd(Paypalpayment::apiContext());
$payment->create(Paypalpayment::apiContext());
// dd($payment);
$arrpayment = $payment->toArray();
$order = Orders::find($saved_order_id);
$order->paypal_invoice = $arrpayment['id'];
$order->save();
} catch (\PPConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData();
dd($ex);
return response()->json(["error" => $ex->getMessage()], 400);
}
catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
}
$email=$request->billing_email;
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$data=array(
'order' => $order,
'name' => $request->billing_first_name.' '.$request->billing_last_name,
'email'=>$email,
'fee'=>$fee,
'payPalLink' => $payment->getApprovalLink(),
);
Mail::send('email.placed', $data, function($message) use ($email) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($email);
});
$admins=DB::table('users')
->select('updates_email')
->where('receiving_updates',1)
->where(function($q) {
$q->where('role','Administrator')
->orWhere('role','Retailer');
})->get()->toArray();
// ->where('role','Administrator')
// ->orWhere('role','Retailer')
// dd($admins);
foreach($admins as $admin){
$admin_mail=$admin->updates_email;
//dd($admin_mail);
Mail::send('email.orderplaced',$data, function($message) use ($admin_mail) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($admin_mail);
});
}
return redirect($payment->getApprovalLink());
// return response()->json([$payment->toArray(), 'approval_url' => $payment->getApprovalLink()],
200);
}
I think the issue is with try catch problem?

Laravel foreach save data

I have a loop for create or update data like below
foreach ($goods_list as $goods) {
$w_estim_mp = WEstimMp::where('event_seq', \LoginInfo::event_data()['event_seq'])
->where('goods_seq', $goods['goods_seq'])
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
if (!isset($w_estim_mp)) {
$w_estim_mp = new WEstimMp;
$w_estim_mp->event_seq = \LoginInfo::event_data();
$w_estim_mp->goods_seq = $goods['goods_seq'];
$w_estim_mp->mp_item_category = $mp_item_category;
}
$w_estim_mp->num = $goods['num'];
$w_estim_mp->note = $goods['note'];
$w_estim_mp->proc_flg = 2;
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
$w_estim_mp->update_dtime = $now;
$w_estim_mp->save();
}
I don't know why i can update only last value of $goods_list.
Help me T.T Thank you!
You can use array_pop to remove the last element and array_push to insert a new element. Follow an example:
<?php
$initial_array = [1,2,3];
function change_last($array, $value) {
$removed_element = array_pop($array);
array_push($array, $value);
return $array;
}
$changed_array = change_last($initial_array, 4);
print_r($changed_array);
?>
and here a live example:
https://tech.io/snippet-widget/ZfEzgjj
I resolved my question!
I don't know why but i work, finnaly, after i changed to
foreach ($goods_list as $goods) {
$goods_seq = $goods['goods_seq'];
$num = $goods['num'];
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
if (!isset($w_estim)) {
$w_estim = new WEstimMp;
$w_estim->event_seq = $event_seq;
$w_estim->goods_seq = $goods_seq;
$w_estim->mp_item_category = $mp_item_category;
$w_estim->num = $num;
$w_estim->note = $goods['note'];
$w_estim->proc_flg = 2;
$w_estim->update_dtime = $now;
$w_estim->save();
} else {
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
// ->first()
->update([
'num' => $num,
'note' => $goods['note'],
'proc_flg' => 2,
'update_dtime' => $now,
]);
}

facebook login returning 0 codeigniter instead of trying many solutions

I trying to get facebook login functionality to work. My problem is that the userid is returning 0. Below is my code.
include_once APPPATH."libraries/facebook-api-php-codexworld/facebook.php";
$appId = 'xxxxx';
$appSecret = 'xxxxx';
$redirectUrll = base_url() . 'register/';
$fbPermissions = 'email';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret
));
$_REQUEST += $_GET;
$fbuser = $facebook->getUser();
print_r($fbuser);
if ($fbuser) {
$userProfile = $facebook->api('/me?fields=id,first_name,last_name,email,gender,locale,picture');
// Preparing data for database insertion
$userData1['oauth_provider'] = 'facebook';
$userData1['oauth_uid'] = $userProfile['id'];
$userData1['fname'] = $userProfile['first_name'];
$userData1['lname'] = $userProfile['last_name'];
$userData1['email'] = $userProfile['email'];
$userData1['status'] = 'Active';
//$userData['gender'] = $userProfile['gender'];
//$userData['locale'] = $userProfile['locale'];
// $userData['profile_url'] = 'https://www.facebook.com/'.$userProfile['id'];
//$userData['picture_url'] = $userProfile['picture']['data']['url'];
// Insert or update user data
$userID = $this->home->checkUser($userData1);
if(!empty($userID)){
$data['userData1'] = $userData1;
$this->session->set_userdata('userData1',$userData1);
} else {
$data['userData1'] = array();
}
} else {
$fbuser = '';
$data['authUrl'] = $facebook->getLoginUrl(array('redirect_uri'=>$redirectUrll,'scope'=>$fbPermissions));
}
You can add this code:
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret,
'cookie' => true
));
$userId = $this->facebook->getUser();
if($userId == 0){
$access['scope'] = 'email,publish_actions,user_birthday,user_location,user_about_me,user_hometown';
$access['redirect_uri'] = base_url() . 'register/';
$url = $this->facebook->getLoginUrl($access);
redirect($url);
}
else
{
$access = $this->facebook->getAccessToken();
$user = $this->facebook->api('/me?fields=first_name,last_name,email,birthday,gender,locale,picture',array('access_token'=>$access));
//echo "<pre>";print_r($user);exit;
$userData1['oauth_provider'] = 'facebook';
$userData1['oauth_uid'] = $user['id'];
$userData1['fname'] = $user['first_name'];
$userData1['lname'] = $user['last_name'];
$userData1['email'] = $user['email'];
$userData1['status'] = 'Active';
$userID = $this->home->checkUser($userData1);
if(!empty($userID))
{
$data['userData1'] = $userData1;
$this->session->set_userdata('userData1',$userData1);
}
else {
$data['userData1'] = array();
}
redirect('/login');//Redirect To Success Page
}
I hope it will work for you!!

Resources