SQLSTATE[23000] - laravel

I have a trouble about phpmyadmin of laravel
I want to update the data from the view on the db via controller but I get an error occurred
// save all seats
foreach ($request->all() as $key => $param) {
if ($key === '_token') continue;
$data = explode('-', $key);
$bs = new BookedSeat();
$bs->booking_id = $booking->id;
$bs->day_id = str_replace('c', '', $data[0]);
$bs->table_id = str_replace('t', '', $data[1]);
$bs->number = 0;
$bs->status = 'requested';
$bs->save();
}
its an error when i try update data
its my db

Updated
// save all seats
foreach ($request->all() as $key => $param) {
if ($key === '_token') continue;
$data = explode('-', $key);
$bs = new BookedSeat();
$bs->booking_id = $booking->id;
$day = DB::table('days')->where('name',$data[0])->get();
$bs->day_id = $day->id;
$bs->table_id = str_replace('t', '', $data[1]);
$bs->number = 0;
$bs->status = 'requested';
$bs->save();
}

Related

Requesting solution for laravel 8 project

I'm an elementary web developer, I'm facing a problem. Please help me solve this. I'm creating both row and column dynamic. for save() is fine. But for update, only name is updated and other item
quantities cannot. Here is my codes.
//for save()
public function stockAdd(Request $request)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$user_id = Auth::user()->user_id;
$stock_id = random_int(100000, 999999);
$stocks = new Stocks();
$stocks->stock_id = $stock_id;
$stocks->owner_id = $user_id;
$stocks->stock_name = request()->stock_name;
$stocks->my_stock = 0;
$stocks->disable = 0;
$stocks->save();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
$stockitems = new StockItems();
$stockitems->stock_id = $stock_id;
$stockitems->product_id = $product->product_id;
$stockitems->owner_id = $user_id;
if(request()->$product_id > 0){
$stockitems->count = request()->$product_id;
}else{
$stockitems->count = 0;
}
$stockitems->save();
}
}
}
return redirect()->back()->with('successAddMsg','Successfully Added');
}
//for update()
public function stockUpdate(Request $request, $id)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$stock = Stocks::findOrFail($id);
$stock->stock_name = request()->stock_name;
$stock->my_stock = 0;
$stock->disable = 0;
$stock->update();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
//dd($product_id);
$stockitemitems = DB::table("stock_items")->select("*")->where("owner_id",Auth::user()->user_id)->where("stock_id",$stock->stock_id)->get();
$stockitems->count = $request->input($product_id);
$stockitems->update();
}
}
}
return redirect(route('user.stock-list'))->with('successAddMsg','Successfully Added');
}
The problem shows like this "Creating default object from empty value"

Laravel Mongodb - Integer value with like operator is not working

I am using this package for my laravel application for the mongodb database: https://github.com/jenssegers/laravel-mongodb
Now, I have and id column which contain integer value like: 32312794972256
Now, I am searching like this:
$filtered = array_filter( $request->all());
$trimmed_array = array_map('trim', $filtered);
$new_arr = [];
foreach( $trimmed_array as $k => $v ) {
if( $k !== 'page' && $k !== 'projectToken' && $k !== 'userId' ) {
if( is_numeric( $v) ) {
$v = (int) $v;
}
$new_arr[] = [$k, 'LIKE', '%'. $v .'%' ];
}
}
Log::info( $new_arr );
$projectToken = $request->input('projectToken');
$userId = $request->input('userId');
$this->set_connection( $projectToken, $userId );
$get_project_id = DB::connection('mysql')->table('projects')->where('token', $projectToken )->get(['id_project'])->first();
$collection = 'products_' . $get_project_id->id_project;
$collection = 'products_103';
if(count($new_arr)) {
$search = DB::connection('mongodb')->collection( $collection )->where($new_arr)->paginate(100);
} else {
$search = DB::connection('mongodb')->collection( $collection )->paginate(100);
}
But above search query is not showing any result for this integer search. Do you know why?

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,
]);
}

Elastica Filter and Query Array

I'm using a form for an advanced search. The form inputs are representative of the data in the elasticsearch index. My model receives an array of filter terms and query terms.
$data = array(
'Filter' => array(
'FilerId' => 14592
),
'Query' => array(
'FiledDate' => '2015-08-06',
),
);
I'm using a foreach loop to create the filter and query
foreach ($data['Filter'] AS $field => $value) {
$filter = new \Elastica\Filter\Term();
$filter->setTerm($field, $value);
$filterArray[] = $filter;
}
foreach ($data['Query'] AS $field => $value) {
$query = new \Elastica\Query\QueryString($value);
$query->setDefaultOperator('AND')
->setDefaultField($field);
$queryArray[] = $query;
}
$query = new \Elastica\Query();
$query
->setFields(['TranId'])
->setQuery($queryArray)
->setFilter($filterArray);
$search->setQuery($query);
$numberOfEntries = $search->count();
$comma_separated = 0;
if ($numberOfEntries) {
foreach ($search->scanAndScroll() as $scrollId => $resultSet) {
$results = $resultSet->getResults();
$totalResults = $resultSet->getTotalHits();
foreach ($results as $result) {
$fields = $result->getFields('TransId');
$transid[] = $fields['TranId'][0];
} // ... handle Elastica\ResultSet
}
$comma_separated = implode(", ", $transid);
}
return array('transactions' => $comma_separated, 'total' => $totalResults);
I am getting an error and I can't find the reason why?
Here is some updated code. I'm getting results but not what I thought I should get.
$boolFilter = new \Elastica\Filter\BoolFilter();
foreach ($data['Filter'] AS $field => $value) {
$term = new \Elastica\Filter\Term();
$term->setTerm($field, $value);
$boolFilter->addMust($term);
}
$boolQuery = new \Elastica\Query\BoolQuery();
foreach ($data['Query'] AS $field => $value) {
$match = new \Elastica\Query\Match();
$match->setFieldQuery($field, $value)
->setFieldAnalyzer($field, 'whitespace')
->setFieldOperator($field, 'AND');
$boolQuery->addMust($match);
}
$query = new \Elastica\Query();
$query
->setFields(['TranId'])
->setQuery($boolQuery)
->setFilter($boolFilter);
//print $error->getError();
print "<pre>";
print_r ($query->toArray());
print "</pre>";
$search->setQuery($query);
$numberOfEntries = $search->count();
$comma_separated = 0;
if ($numberOfEntries) {
foreach ($search->scanAndScroll() as $scrollId => $resultSet) {
$results = $resultSet->getResults();
$totalResults = $resultSet->getTotalHits();
foreach ($results as $result) {
$fields = $result->getFields('TransId');
$transid[] = $fields['TranId'][0];
} // ... handle Elastica\ResultSet
}
$comma_separated = implode(", ", $transid);
}
return array('transactions' => $comma_separated, 'total' => $totalResults);
Alright! I needed to add the Standard analyzer instead of the whitespace analyzer. The whitespace analyzer works but only breaks the phrase up on spaces. The standard analyzer breaks the phrase up and make the case lower.
https://www.elastic.co/guide/en/elasticsearch/guide/current/analysis-intro.html#analyze-api
$boolFilter = new \Elastica\Filter\BoolFilter();
foreach ($data['Filter'] AS $field => $value) {
$term = new \Elastica\Filter\Term();
$term->setTerm($field, $value);
$boolFilter->addMust($term);
}
$boolQuery = new \Elastica\Query\BoolQuery();
foreach ($data['Query'] AS $field => $value) {
$match = new \Elastica\Query\Match($value);
$match->setFieldQuery($field, $value);
$match->setFieldAnalyzer($field, 'standard');
$boolQuery->addMust($match);
}
$filterQuery = new \Elastica\Query\Filtered();
$filterQuery->setFilter($boolFilter);
$filterQuery->setQuery($boolQuery);
$query = new \Elastica\Query($filterQuery);
$query->setFields(['TranId']);
print "<pre>";
print_r ($query->toArray());
print "</pre>";
$search->setQuery($query);
$numberOfEntries = $search->count();
$comma_separated = 0;
if ($numberOfEntries) {
foreach ($search->scanAndScroll() as $scrollId => $resultSet) {
$results = $resultSet->getResults();
$totalResults = $resultSet->getTotalHits();
foreach ($results as $result) {
$fields = $result->getFields('TransId');
$transid[] = $fields['TranId'][0];
} // ... handle Elastica\ResultSet
}
$comma_separated = implode(", ", $transid);
}
return array('transactions' => $comma_separated, 'total' => $totalResults);

Resources