I have a controller where an array of checkbox values are passed on to the controller and then sent on to do a variety of tasks. My problem is focused on getting a count of the arrays' shipment's customer's billing method, but I'm not entirely sure how I would get those values since I'm posting an array and I want a count.
Here's my controller:
public function sendNow(Request $request)
{
$now = Carbon::now();
$sendNowShipment = array();
$method = array();
$sendNowShipment = request('send');
foreach($sendNowShipment as $SNS){
$shipment = Shipment::findOrFail($SNS);
if($shipment->billtoAccount->billingMethods->label == "Mail"){
$timestamp = Carbon::now()->timestamp;
$shipment_details = $shipment->shipment_details;
$path = 'temp/freightbill_'.$shipment->pro_number.'-'.$timestamp.'.pdf';
$sessionPath[] = $path;
$pdf = PDF::loadView('shipments.pdf', compact('shipment', 'shipment_details'))
->save($path);
}elseif($shipment->billtoAccount->billingMethods->label == "Email"){
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
if ($billToAccount->primary_email){
$billToEmail[] = $billToAccount->primary_email;
}
if ($billToAccountUsers->count() > 0){
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail[] = $billToAccountUser->email;
}
}
foreach ($billToEmail as $bte){
Mail::to($bte)->send(new newBillToShipment($shipment));
}
}
}
if(count($shipment->billtoAccount->billingMethods->label == "Mail") > 0){// count where shipments->customers->billingMethods = Mail) > 0
$pdf = new PDFMerger();
// Add 2 PDFs to the final PDF
foreach($sessionPath as $sp){
$pdf->addPDF($sp, 'all');
}
// Merge the files and retrieve its PDF binary content
$timestamp = Carbon::now()->timestamp;
$binaryContent = $pdf->merge('download', $timestamp."-printBatch.pdf");
// Return binary content as response
//return response($binaryContent)
// ->header('Content-type' , 'application/pdf');
return back();
//dd($sendNowShipment,$sendMethod);
}
}
If you look at this line (a little past the middle):
if(count($shipment->billtoAccount->billingMethods->label == "Mail") > 0){
// count where shipments->customers->billingMethods = Mail) > 0
You'll see that I'm going through a multitude of relationships just to get the value of "Mail" that I am looking for.
So I'm wondering if this should be a DB:: query through laravel, but I'm not sure how I would perform the query using the given checkbox array I have being POSTed to this controller.
Related
I call a function, and I want to get a response with an array and two elements per key.
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/_giveRandomQuestSearchPok.php');
$pokQ = QuestPoks::giveRandomQuestPok();
The function itself looks like this
public static function giveRandomQuestPok() {
$sC = \Work::$sql->prepare('SELECT region FROM users WHERE id = ?');
$sC->bind_param("i", $_SESSION['id']);
$sC->execute();
$dA = $sC->get_result();
$region = $dA->fetch_assoc();
if($region['region'] == 1){
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/randomPoks/Kanto.php');
}elseif($region['region'] == 3){
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/randomPoks/Hoenn.php');
}
$rarity = mt_rand(1,100);
if($rarity == 1){
$rare = 1;
$object = \matsuka\Rare[mt_rand(0, count(\matsuka\Rare) - 1)];
}elseif($rarity > 1 && $rarity <= 33){
$rare = 2;
$object = \matsuka\Uncommon[mt_rand(0, count(\matsuka\Uncommon) - 1)];
}else{
$rare = 3;
$object = \matsuka\Common[mt_rand(0, count(\matsuka\Common) - 1)];
}
$array = array();
$array['pok'] = $object;
$array['rare'] = $rare;
return $array;
}
After executing the function I want to assign two variables to control the result
$pok = $pokQ["pok"];
$rare = $pokQ["rare"];
But the handler still reads them as an array.
And when I paste it into sql I get an Array, although I was hoping to get the array data by their corresponding key.
In var_dump I get quite a strange answer. I seem to see the required value of array called by the key, but on top of that I see another array, if I understand correctly.
int(401)
{
"name":"\u0413\u0443\u0441\u0442\u0430\u0432",
"actionQuest":"<img src=\"\/img\/quests\/7.webp\" class=\"quest\"> \u041e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0430 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u0432 \u0437\u0430\u0434\u0430\u043d\u0438\u0438 \u00ab\u041f\u043e\u043c\u043e\u0449\u044c \u0441\u0442\u0430\u0440\u043e\u043c\u0443 \u043f\u0440\u0438\u044f\u0442\u0435\u043b\u044e\u00bb. \u0417\u0430\u0433\u043b\u044f\u043d\u0438\u0442\u0435 \u0432 \u0410\u043a\u0432\u0430\u0431\u0443\u043a.",
"question":"\u0422\u044b \u043e\u0442\u043b\u0438\u0447\u043d\u043e \u0441\u043f\u0440\u0430\u0432\u0438\u043b\u0441\u044f \u0441 \u043c\u043e\u0438\u043c \u043f\u0440\u043e\u0448\u043b\u044b\u043c \u0437\u0430\u0434\u0430\u043d\u0438\u0435\u043c. \u042f \u0445\u043e\u0440\u043e\u0448\u0435\u043d\u044c\u043a\u043e \u0438\u0437\u0443\u0447\u0438\u043b \u0442\u043e\u0433\u043e \u043f\u043e\u043a\u0435\u043c\u043e\u043d\u0430. \u0422\u0435\u043f\u0435\u0440\u044c \u043c\u043d\u0435 \u043d\u0443\u0436\u0435\u043d: <div class=\"questPokemon\"><img src=\"\/img\/pokemons\/mini\/normal\/Array.webp\"> <div>#Array <\/div><\/div>"
}
Why does this happen and what is my mistake?
In the array I should only get 3-digit numbers under each key
Currently I'm using Mysql and CodeIgniters MVC framework to fill in my data. The table logs every status change that has been made and when it was made. This is what the database currently looks like:
I've added new columns in the table called status_from and status_to, where I want these columns to take the substring from action column.
But now how do I display it in my database with my following code:
Controller class:
public function status($status){
$statusar = array('D'=>'Draft','N'=>'Unpublish','Y'=>'Publish','U'=>'Action','L'=>'Unlisted','S'=>'Sold','T'=>'Let');
if($this->input->post('id')){
foreach($this->input->post('id') as $key => $id):
$check = $this->listings_model->loadlisting_check($id);
$log = "Listing website status changed from ". $statusar[$check->status]." to ".$statusar[$status].". The listing ID is #".$id.".";
$this->logs_model->insert_log(array('refno'=>$check->refno,'action'=>trim($log)));
$data=array('status'=>$status);
if($status == 'T' || $status == 'Y' || $status == 'S'){
$pub = 1;
}else{
$pub =0;
}
$this->listings_model->lpupdate(array('property_publish'=>$pub),$id);
endforeach;
}
return true;
}
listings_model:
function loadlisting_check($id)
{
$this->db->select("refno, status, archive");
$id=$this->db->escape_str($id);
$cond=array("$this->table_name.$this->primary_key"=>$id);
$this->db->where($cond);
$this->db->from($this->table_name);
$query = $this->db->get();
return $query->row();
}
logs_model:
public function insert_log($log)
{
$log['agent_id'] = $this->session->userdata('clientsessuserid');
$log['logtime'] = date('Y-m-d H:i:s');
$this->db->insert($this->table_name, $log);
return true;
}
Basically I want to fill my status_from column with $statusar[$check->status] and status_to column with $statusar[$status] when every new entry is made
You can pass the variables you want to add in the array in insert_log method parameter with proper key matched with column name in your table
public function status($status){
$statusar = array('D'=>'Draft','N'=>'Unpublish','Y'=>'Publish','U'=>'Action','L'=>'Unlisted','S'=>'Sold','T'=>'Let');
if($this->input->post('id')){
foreach($this->input->post('id') as $key => $id):
$check = $this->listings_model->loadlisting_check($id);
$log = "Listing website status changed from ". $statusar[$check->status]." to ".$statusar[$status].". The listing ID is #".$id.".";
$this->logs_model->insert_log(array('refno'=>$check->refno,'action'=>trim($log) , 'status_from'=>$statusar[$check->status] ,'status_to'=>$statusar[$status]));
$data=array('status'=>$status);
if($status == 'T' || $status == 'Y' || $status == 'S'){
$pub = 1;
}else{
$pub =0;
}
$this->listings_model->lpupdate(array('property_publish'=>$pub),$id);
endforeach;
}
return true;
}
And you will not need to add anything else to your model
I seem to be stuck. I have a funtion that calculates the salary. I am trying to make it so that I can specify one or many users when I call the function. But I ran into 2 problems. One is how could I construct the output result if I specify multiple user ids. And second problem is how not to repeat my code twice (for one and many users). It works fine if I only need to get it for one user.
I would like to be able to call it like this:
// Get salary for user id: 10
$salary = Salary::getSalary([10], '2018-12-01', '2018-12-31');
echo $salary->user->fullname;
echo $salary->salary->total;
echo $salary->checked;
// Get salary for users - 10, 20, 30
$salaries = Salary::getSalary([10, 20, 30, '2018-12-01', '2018-12-31');
foreach ($salaries as $salary) {
echo $salary->user->fullname;
echo $salary->salary->total;
echo $salary->checked;
}
Here is my function
public function getSalary($user_id, $date_from, $date_to)
{
$salary = new stdClass;
if ( count($user_id) == 1 ) {
$salary->user = new stdClass;
$salary->user->fullname = self::getUserById($user_id)->fullname;
$salary->user->phone = self::getPhone($user_id);
$salary->user->email = self::getUserById($user_id)->e_mail;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
} else if ( count($user_id) > 1 ) {
foreach ($user_id as $employee)
{
$salary->employee = new stdClass;
$salary->employee->fullname = self::getUserById($user_id)->fullname;
$salary->employee->phone = self::getPhone($user_id);
$salary->employee->email = self::getUserById($user_id)->e_mail;
$salary->employee->siawork = self::getUserById($user_id)->siawork;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
}
}
return $salary;
}
I think if when you call the function and there is only 1 entry, then you can convert this to an array so that you always use the same code to process the data, and build an array of the salary data to send back...
public function getSalary($user_id, $date_from, $date_to)
{
$salaries = [];
if ( !is_array($user_id) ) {
$user_id = [$user_id];
}
foreach ($user_id as $employee)
{
$salary->employee = new stdClass;
$salary->employee->fullname = self::getUserById($user_id)->fullname;
$salary->employee->phone = self::getPhone($user_id);
$salary->employee->email = self::getUserById($user_id)->e_mail;
$salary->employee->siawork = self::getUserById($user_id)->siawork;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
$salaries[] = $salary;
}
return $salaries;
}
You could if you wish, return a single entry if you want to by amending the last part of the code...
if ( count($user_id) == 1 ) {
$salaries = $salaries[0];
}
return $salaries;
}
Here's my solution for your class function. It looks like you were trying to return a single object and overwriting employee every time. If you can accept an array of ID's, it makes sense to return an array of salaries. Does this make sense?
public function getSalary($user_id, $date_from, $date_to)
{
//Return an array of salary objects to match your array of id inputs
$salary = [];
if ( ! is_array($user_id) ) {
//In case a non-array is entered
$user_id = [$user_id];
}
// A foreach will work even if there's only one user ID given,
// as long as it's an array (which it should be by this point)
foreach ($user_id as $id)
{
//Get your salary object by id
$this_user = new stdClass;
$this_user->user = new stdClass;
$this_user->user->fullname = self::getUserById($id)->fullname;
$this_user->user->phone = self::getPhone($id);
$this_user->user->email = self::getUserById($id)->e_mail;
$this_user->salary = self::getSalary($id, $date_from, $date_to);
$this_user->checked = self::isChecked($id, $date_from, $date_to);
//Put it in the output array
$salary[] = $this_user;
}
return $salary;
}
Note, please validate all these inputs! Make sure that putting in something unexpected to $user_id or $date_from or $date_to will not break everything without at least showing an error.
I am trying to get all Ad Schedules placed in Google Ads through the Google Ads API and obtain the start and end times (hour and minute) to compare it with some existing values and depending on whether they differ update accordingly.
Here is my code showing where I am iterating over returned Ad Schedules.
foreach($campaigns as $camp) {
// Get restaurant and details
$res = RestaurantsService::getRestaurantByName($camp->getName());
$hours =$res->getHours()->dequeue();
$start = explode("-",$hours)[0];
$end = explode("-",$hours)[1];
// Get current ad schedules as they are now
$campaignAdSchedules = self::getCampaignAdSchedule($campaignCriterionService,$camp->getId());
if ($campaignAdSchedules == null){
$operations = [];
$schedule = new AdSchedule();
$schedule->setDayOfWeek(self::DAYS[date("N")-1]);
$schedule->setStartHour((int)substr($start,0,2));
$schedule->setStartMinute(MinuteOfHour::ZERO);
$schedule->setEndHour((int)substr($end,0,2));
$schedule->setEndMinute(MinuteOfHour::ZERO);
$operation = new CampaignCriterionOperation();
$criterion = new CampaignCriterion();
$criterion->setCampaignId($camp->getId());
$criterion->setCriterion($schedule);
$operation->setOperand($criterion);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
$campaignCriterionService->mutate($operations);
} else {
foreach($campaignAdSchedules as $adSchedule){
---> $schedule = $adSchedule->getCriterion(); <---
}
}
}
Here the line marked with arrows is the line I am having problems with. The getCriterion() function returns a Criterion object which does not have the methods getStartHour() etc. I have tried casting it but haven't found the correct way.
Help is much appreciated!
Try check the instance:
$result = $campaignCriterionService->get($serviceSelector);
$campaignAdSchedules = $result->getEntries();
foreach ($campaignAdSchedules as $criterion) {
$adSchedule = $criterion->getCriterion();
if ($adSchedule instanceof AdSchedule) {
$adSchedule->getStartHour();
}
}
I have five text fields that are not mandatory. Sometimes enter data in one field, sometimes 2 or 3 or 4 or 5. I have to count this data:
$sib1=$this->input->post(sib1);
$sib2=$this->input->post(sib2);
$sib3=$this->input->post(sib3);
Like this, I want to count this. Now 3
You can use a for loop with length = number of text fields. Put it to the database afterwards. sibcount is the number of filled entries.
$data = array();
$length = 5;
$sibcount = 0;
for ($i=0;$i<$length;$i++) {
$entry = $this->input->post("sib".$i);
if (!empty($entry)) {
$data["sib".$i] = $entry;
$sibcount++;
}
}
$data["sibcount"] = $sibcount;
// use in controller or model
if (!empty($data))
$this->db->insert('mytable', $data);
this is way to do it:
Take an array $arr=array();
$arr['sib1']=$this->input->post("sib1",true);
$arr['sib2']=$this->input->post("sib2",true);
$arr['sib3']=$this->input->post("sib3",true);
$arr['count']=count($this->input->post($arr)); //this will count your post
$result = $this->Model_name->model_function($arr);
In Model
function model_function($arr)
{
$this->db->insert('tbl',$arr);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}