I'm currently creating API for multiple inputs using laravel. The data will be stored into two tables : Order and Detail_Order. One order can have many detail orders.
But now, the data only stored into Order table, and got an error: ErrorException: Invalid argument supplied for foreach() in file. Does anyone know how? Thank you.
Here's my code :
public function createDetail($total_passenger, $id_trip, $id_users, Request $request){
$trip = Trip::where(['id_trip' => $id_trip])->get();
$seat = $request->id_seat;
if(Detail_Order::where(['id_trip' => $id_trip, 'id_seat' => $seat])
->where('status', '!=', 5)
->exists()) {
return $this->error("Seat has been booked");
}else{
$order = new Order();
$order_select = Order::select('id_order');
$order_count = $order_select->count();
if ($order_count === 0) {
$order->id_order = 'P1';
}else{
$lastrow=$order_select->orderBy('created_at','desc')->first();
$lastrow_id = explode('P', $lastrow->id_order);
$new_id = $lastrow_id[1]+1;
$order->id_order = 'P'.$new_id;
}
$order->id_trip = $id_trip;
$order->id_users = $id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = 'O4';
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'gender' => $request->gender[$key],
'departure' => $request->departure[$key],
'destination' => $request->destination[$key],
'phone' => $request->phone[$key],
'status' => 1
]);
}
return response()->json([
'status' => true,
'message' => "Successfully saved data",
'data' => $order
]);
}
Related
This is my code. I don't know what should I do now, because I'mm really confused in this problem.
in Controller for CSV Import
function import()
{
$this->load->library('csvreader');
$result = $this->csvreader->parse_file('./application/upload/financialloss.csv');
foreach($result as $value=>$key){
$date_report = date("Y-m-d H:i:s");
$handlingdate = $key['Handling Date'];
$handlingdate2 = strtotime($handlingdate);
$handlingdate3 = date('Y-m-d',$handlingdate2);
$nominal_awal = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $key['Transactions Nominal'])));
$nominal = str_replace(",","", $key['Transactions Nominal']);
$nominal1 = str_replace(".","", $nominal);
$nominal2 = str_replace("Rp","", $nominal1);
$tblfinancialloss = array(
'handlingdate' => $handlingdate3,
'lossdate' => $key['Loss Date'],
'ticketid' => $key['Ticket ID'],
'reporteremail' => $key['Reporter Email'],
'reporterusername' => $key['Reporter Username'],
'transactionsfraud' => $key['Transactions Fraud'],
'transactionsfinancialloss' => $key['Transactions Financial Loss'],
'transactionsnominal' => $nominal2,
'cityofuser' => $key['City of User'],
'provinceofuser' => $key['Province of User'],
'transactionscategory' => $key['Transactions Category'],
'casecategory' => $key['Case Category'],
'sourcedata' => $key['Source Data'],
'linkphisingmedia' => $key['Link Phising Media'],
'notesloss' => $key['Notes'],
'dateinput' => $date_report,
'inputby' => "by ".$this->session->userdata('name')
);
if(empty($key['Loss Date'])){
$this->session->set_flashdata('msg','TES1');
redirect(base_url()."index.php/DashboardFinancial/AddFinancialLoss");
}
else{
$this->Csv_Import_model->insert($tblfinancialloss);
$this->session->set_flashdata('msgs',' data, uploaded today !');
}
}
//unlink('./assets/data.csv');
}
And this is My Model for CSV Import
function insert($data)
{
$this->dbfinanciallossandsave= $this->load->database('financiallossandsave', TRUE);
$insert_query1 = $this->dbfinanciallossandsave->insert_string('tblfinancialloss', $data);
$insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query1);
$date = date("Y-m-d");
$this->dbfinanciallossandsave->where('handlingdate <=', $date);
//$this->dbfinanciallossandsave->where('lossdate <=', $date);
$this->dbfinanciallossandsave->query($insert_query);
}
And my model for where condition can't work. Can you help me?
I am trying to insert $product, $pric and $user to database table cart. Following is the function that I have created in SiteController.php.
public function actionCartadd($id)
{
$product = Additem::find()
->select('product')
->where(['id' => $id])
->one();
$pric = Additem::find()
->select('price')
->where(['id' => $id])
->one();
$user = Yii::$app->user->identity->username;
$connection = Yii::$app->getDb();
$result = Yii::$app->db->createCommand()
->insert('cart', [
'product' => '$product',
'price' => '$pric',
'user' => '$user',
])->execute();
if ($result)
return $this->render('custstore');
}
However, this end up in error. Can anyone suggest any fix
Try this following code
$result = Yii::$app->db->createCommand()->insert('cart', [
'product' => $product->product,
'price' => $pric->price,
'user' => $user
])->execute();
Look at this fragment:
'product' => '$product',
'price' => '$pric',
'user' => '$user',
Use double quotes in values or just variables without quotes
Also, better way to fetch product and price:
$productItem = Additem::findOne($id);
if ($productItem instanceof Additem) {
$product = $productItem->product;
$pric = $productItem->price;
}
I am trying to insert some record by checking if certain conditions are met. What I am planning to do is to restrict the users from voting twice daily. I am using email and date as parameters.
public function store(Request $request)
{
$this->validate($request, [
'flavour' => 'required|string',
'email' => 'required|email',
'lastname'=> 'required|string',
'firstname' => 'required|string'
]);
$vote = new Vote();
//$currentDate = Carbon::now()->toDateString();
$today = Carbon::now()->format('Y-M-D');
$dup = Vote::where(['email' => $request->email, 'created_at' => $today ])->get();
if (!$dup)
{
$vote->firstname = $request->firstname;
$vote->lastname = $request->lastname;
$vote->email = $request->email;
$vote->flavour = $request->flavour;
$vote->voter_ip = $request->ip();
}
else {
return response()->json([
'message' => 'You have voted today, please wait till another day!'
]);
}
if (auth()->user()->votes()->save($vote))
return response()->json([
'success' => true,
'data' => $vote->toArray()
]);
else
return response()->json([
'success' => false,
'message' => 'Vote could not be added'
], 500);
}
The problem I am encountering now is, it doesn't take any record as it keeps displaying the message "You have voted today, please wait till another day", even if I insert a new email and/or a current user with different emails.
First, I had to create a field in my migration called "voted_at" and rearranged the code to check for the existing record based on the voted_at and email of the user
public function store(Request $request)
{
$this->validate($request, [
'flavour' => 'required|string',
'email' => 'required|email',
'lastname'=> 'required|string',
'firstname' => 'required|string'
]);
$today = Carbon::now()->toDateString();
$dup = Vote::where(['email' => $request->email, 'voted_at' => $today ])->exists();
if ($dup){
return response()->json([
'data' => $dup,
'message' => 'You have voted today, please wait till another day!'
]);
}
else {
$vote = new Vote();
$vote->firstname = $request->firstname;
$vote->lastname = $request->lastname;
$vote->email = $request->email;
$vote->flavour = $request->flavour;
$vote->voter_ip = $request->ip();
$vote->voted_at = $today;
if (auth()->user()->votes()->save($vote))
return response()->json([
'success' => true,
'data' => $vote->toArray()
]);
else
return response()->json([
'success' => false,
'message' => 'Vote could not be added'
], 500);
}
}
Thanks
I'm yet to understand what needed to be fixed in the code making it to generate the error. What is to be put right?
This is the code:
public function store(Request $request){
$validator = Validator::make($request->all(), [
'user_id' => 'required|numeric',
'company_id' => 'required|numeric',
'product_id' => 'required|numeric',
'tankerTotankerDesc' => 'alpha_num|min:5',
'tankerTakeOverDesc' => 'alpha_num|min:5',
'costFreightInsuranceDesc' => 'alpha_num|min:5',
'freightOnBoardDesc' => 'alpha_num|min:5',
'tankerTotankerPrice' => 'numeric|required_with:tankerTotankerDesc',
'tankerTakeOverPrice' => 'numeric|required_with:tankerTakeOverDesc',
'costFreightInsurancePrice' => 'numeric|required_with:costFreightInsuranceDesc',
'freightOnBoardPrice' => 'numeric|required_with:freightOnBoardDesc',
'optional_procedure' => 'alpha_num|min:5',
'optional_procedure_price' => 'numeric|required_with:optional_procedure',
'business_type' => 'required'
]);
if ($validator->fails()) {
redirect()->route('productUniqueCreate', $validator)->with('message', 'Record successfully created');
}else{
$product_id = $request->product_id;
$procurementUnique = ProcurementUnique::firstOrNew(array('product_id'=>$product_id));
$procurementUnique->user_id = $user_id;
$procurementUnique->company_id = $request->company_id;
$procurementUnique->product_id = $product_id;
$procurementUnique->productname = $request->productname;
$procurementUnique->ttt_description = $request->tankerTotankerDesc;
$procurementUnique->tto_description = $request->tankerTakeOverDesc;
$procurementUnique->cif_description = $request->costFreightInsuranceDesc;
$procurementUnique->fob_description = $request->freightOnBoardDesc;
$procurementUnique->optional_procedure = $request->optional_procedure;
$procurementUnique->ttt_price = $request->tankerTotankerPrice;
$procurementUnique->tto_price = $request->tankerTakeOverPrice;
$procurementUnique->cif_price = $request->costFreightInsurancePrice;
$procurementUnique->fob_price = $request->freightOnBoardPrice;
$procurementUnique->optional_procedure_price = $request->optional_procedure_price;
$procurementUnique->business_type = $request->business_type;
$procurementUnique->save();
return redirect()->route('productUniqueCreate', $product_id)->with('message', 'Record successfully created');
}
}
Your problem is with this line..
redirect()->route('productUniqueCreate', $validator)->with('message', 'Record successfully created');
Remove the $validator.
redirect()->route('productUniqueCreate')->with('message', 'Record successfully created')->withErrors($validator);
I have problem with counterCache in cakePHP 2.6.4.
I need to save multiple rows to bloggers_products table and i want to increment Bloggers.products_all for each product. For now products_all is allways incremented once.
BloggersProduct belongsTo Blogger
Blogger hasMany BloggersProduct
BloggersProduct Model
'Blogger' => array(
'className' => 'Blogger',
'counterCache' => array(
'products_all' => true,
'reviews' => array('NOT' => array('BloggersProduct.review' => '0000-00-00'))
)
)
I was trying to save data in loop and with saveMany.
$i = 0;
$save = [];
$this->loadModel('BloggersProduct');
foreach ($data as $product) {
// $save = [];
// $save['product_id'] = intval($product);
// $save['blogger_id'] = $blogger_id;
// $save['send_at'] = date('Y-m-d', time());
//
// $this->BloggersProduct->create();
// $this->BloggersProduct->save($save, array('counterCache' => true));
$save[$i]['product_id'] = intval($product);
$save[$i]['blogger_id'] = $blogger_id;
$save[$i]['send_at'] = date('Y-m-d', time());
$i++;
}
debug($save);
$res = $this->BloggersProduct->saveMany($save, array('counterCache' => true));
When i edit or delete any of related products counters set to true value.
Answer was simple:
$this->YourModel->cacheQueries = false;