Eloquent: get data for every day of the month - laravel

I have some troubles with my Eloquent query result formatting.
I have the table Clubs and it stores football clubs. Every record in database has 'brand' value and now I want to return count of column brand values for every day. For example: I added today 9 times "Real" and 40 times "Barcelona" to my table, so I expect return value for every day in the last month like:
[
{
"date": "2019-01-12",
"clubs": {
"Barcelona": 40,
"Real": 9
}
}
]
Instead of that I get:
[
{
"date": "2019-01-12",
"count": 9,
"brand": "Real"
},
{
"date": "2019-01-12",
"count": 40,
"brand": "Barcelona"
}
]
There's my controller query:
$brandsMonthlyInfo = array();
$dates = collect();
foreach( range( -30, 0 ) AS $i ) {
$date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
$dates->put( $date, 0);
}
$countAddedBrands = DB::table('Clubs')->where([['created_at', '>=', $dates->keys()->first()]])
->groupBy( 'date' )
->groupBy( 'brand' )
->orderBy( 'date' )
->get( [
DB::raw( 'DATE( created_at ) as date' ),
DB::raw( 'COUNT(brand) AS "count"' ),
'brand'
] );
return $countAddedBrands;
Do you have any idea how to fix that? I really appreciate any help.

you can transform the data like this
$brandsMonthlyInfo = array();
$dates = collect();
foreach( range( -30, 0 ) AS $i ) {
$date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
$dates->put( $date, 0);
}
$countAddedBrands = DB::table('Clubs')->where([['created_at', '>=', $dates->keys()->first()]])
->groupBy( 'date' )
->groupBy( 'brand' )
->orderBy( 'date' )
->get( [
DB::raw( 'DATE( created_at ) as date' ),
DB::raw( 'COUNT(brand) AS "count"' ),
'brand'
] );
// create the array to contain the objects
$arrayOfAddedBrands = [];
foreach($countAddedBrands as $brand){
$found = 0;
// looping over the array to search for the date if it exists
foreach($arrayOfAddedBrands as $key => $brandFromArray ){
// if the date exists
if($brand->date == $brandFromArray->date){
// add the brand to the clubs object
$brandFromArray->clubs->{$brand->brand} = $brand->count;
$found = 1;
// assign the array element to the new modified object
$arrayOfAddedBrands[$key] = $brandFromArray;
break;
}
}
// if the date not found
if(!$found){
// create new object and assign the date to it
$brandObject = new \stdClass;
$brandObject->date = $brand->date;
// creating the clubs object
$brandObject->clubs = new \stdClass;
$brandObject->clubs->{$brand->brand} = $brand->count;
// adding the final object to the array
$arrayOfAddedBrands[] = $brandObject;
}
}
return $arrayOfAddedBrands;

Related

Invalid Datetime format: 1366 Incorrect integer value LARAVEL

I'm trying to update or insert multiple data when a post approve. Insert condition is working but update function giving error.
(SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer
value: '[10000,10000]' for column
parijattech_web_app.palika_to_school_kriyakalap.cash at row 3 update
palika_to_school_kriyakalap SET cash = [ 10000, 10000 ],
palika_to_school_kriyakalap.updated_at = 2022 -12 -26 04: 58: 52 WHERE
kriya_name IN (SALARY, POSHAK) AND school_id IN (24, 24))
My code is so messy. So, how can i improve my coding skill?
Here is my Controller
public function approve(Request $request, $biniyojan_id)
{
$upudate = DB::table('biniyojan')
->where('biniyojan_id', $biniyojan_id)
->update(['biniyojan_status' => 1]);
if ($upudate) {
$budget_data = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)->where('biniyojan_id', $biniyojan_id)->get();
$kriya = Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
->whereIn('school_id', $budget_data->pluck('school_id'))
->get();
$budget_cash = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)
->whereIn('school_id', $kriya->pluck('school_id'))
->whereIn('kriyakalap', $kriya->pluck('kriya_name'))
->get();
$updated_bini = $budget_cash->pluck('cash')->toArray();
$updated_kriya_cash = $kriya->pluck('cash')->toArray();
$newArray = array_map(function () {
return array_sum(func_get_args());
}, $updated_bini, $updated_kriya_cash);
if ($kriya->pluck('school_id') == $budget_data->pluck('school_id')) {
Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
->whereIn('school_id', $budget_data->pluck('school_id'))
->update(['cash' => $newArray]);
} else {
foreach ($budget_data as $bud) {
$data = [
'school_id' => $bud->school_id,
'kriya_name' => $bud->kriyakalap,
'cash' => $bud->cash,
];
Palika_ToSchool_Kriyakalap::where('kriya_name' != $bud->kriyakalap)
->insert($data);
}
}
return redirect()->back()->with('status', 'Approved!!!');
}
else{
return redirect()->back()->with('error', 'Error!!!');
}
}

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

How to update row which have unique id in Codeigniter

I have a table which has a field of customer_number, some numbers repeat many times but I want to get only that number which is unique in filed.
public function set_unique()
{
$e = $_POST['e'];
if($e == 1)
{
$one = $this->db->get('calls_details');
foreach($one->result() as $data) {
$two = $this->db->where('Customer_Number', $data->Customer_Number)
->get('calls_details');
if($two->num_rows() == 1) {
foreach($two->result() as $data2) {
$three = $this->db->where('Customer_Number', $data2->Customer_Number)
->update('calls_details', ['unique_id'=>1]);
}
}
}
}
}
}
// defining array in which we get form values
$dataDB = ['first_name' => $this->input->post('first_name'),
'second_name' => $this->input->post('second_name'),
'email' => $this->input->post('email'),
];
// load model
$this->load->model('Customer');
//set record id, which we need to be updated
$this->Customer->id = $uniqueCustomerIDNumber;
//save record
$this->Customer->save();

render data from array to select option laravel

function getAllYears()
{
$year_array = array();
$posts_dates = Entries::orderBy( 'created_at', 'ASC' )->pluck( 'created_at' );
$posts_dates = json_decode( $posts_dates );
if ( ! empty( $posts_dates ) )
{
foreach ( $posts_dates as $unformatted_date )
{
$date = new \DateTime( $unformatted_date->date );
$year_value = $date->format( 'Y' );
$year_val = $date->format( 'y' );
//$year_array[$year_val ] = $year_value;
$year_array[] = $year_value;
}
} //return $year_array;
$array = $year_array;
// Deleting the duplicate items
$unique_years = array_unique($array);
return view('welcome',compact($unique_years));
<select name="YearFrom" id="YearFrom_input"">
<option selected="selected">Choose Year</option>
#foreach($unique_years as $years)
<option value='{{$years}}'> {{$years['years']}} </option>
#endforeach
</select>
!!getting error!!
compact(): Undefined variable: 2009
compact thinks the values of your array are the variables names, because you've passed it the actual array, not the name of the variable. See http://php.net/compact for details on how compact() works. Instead, you need:
return view('welcome',compact('unique_years'));
That said, I hate the compact approach for this reason. This is much more readable:
return view('welcome')->with('unique_years', $unique_years);
Your variabel name was incorrect in compact() - should be a string like 'variable_name' rather than $variable_name
function getAllYears()
{
$year_array = array();
$posts_dates = Entries::orderBy( 'created_at', 'ASC' )->pluck( 'created_at' );
$posts_dates = json_decode( $posts_dates );
if ( ! empty( $posts_dates ) ) {
foreach ( $posts_dates as $unformatted_date ) {
$date = new \DateTime( $unformatted_date->date );
$year_value = $date->format( 'Y' );
$year_val = $date->format( 'y' );
//$year_array[$year_val ] = $year_value;
$year_array[] = $year_value;
}
} //return $year_array;
$array = $year_array;
// Deleting the duplicate items
$unique_years = array_unique($array);
return view('welcome',compact('unique_years'));
}

Magento How to update bundle product programmatically

I am reading product sku from csv file and my csv file contains bundle product sku. I am traversing through csv data and for each bundle sku I want to add bundle items inside it which I am passing through CSV
Here is the code what I have done
ini_set('auto_detect_line_endings', TRUE);
$magentoPath = getcwd();
require_once ($magentoPath . '/includes/config.php');
require_once ($magentoPath . '/app/Mage.php');
Mage::app();
//read the csv
$bundleCsv = Mage::getBaseDir('var').'/import/bundleImport.csv';
$rows = array_map('str_getcsv', file($bundleCsv));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
echo Mage::app()->getStore()->getId(); exit;
foreach( $csv as $key => $val ){
if( !isset($val['sku']) || empty($val['sku']) || $val['sku'] == '' ){
echo 'Not Valid Sku';
continue;
}
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$val['sku']);
$opt = $val['bundle_options'];
$optArr = explode(':', $opt);
$bundleOptions = array();
$bundleSelections = array();
foreach ( $optArr as $key1 => $val1 ) {
$valTemp = explode( '(', $val1 );
$title = trim($valTemp[0]);
$bundleSub[$key1] = array(
'title' => $title, // option title
'option_id' => $key1,
'delete' => '',
'type' => 'select', // option type
'required' => '1', // is option required
'position' => '1' // option position
);
$skuStr = trim($valTemp[1]);
$skuStrTemp = explode( ')', $skuStr );
$skuStr = trim($skuStrTemp[0]);
$skuTemp = explode( '+', $skuStr );
foreach( $skuTemp as $key2 => $val2 ){
$product = Mage::getModel('catalog/product');
$id = Mage::getModel('catalog/product')->getResource()->getIdBySku($val2);
if( $id ){
$bundleSelectionsSub[$key2] = array ( // selection ID of the option (first product under this option (option ID) would have ID of 0, second an ID of 1, etc)
'product_id' => $id, // if of a product in selection
'delete' => '',
'selection_price_value' => '10',
'selection_price_type' => 0,
'selection_qty' => 1,
'selection_can_change_qty' => 0,
'position' => 0,
'is_default' => 1
);
$product = null;
}else{
continue;
}
}
$bundleSelections[$key1] = $bundleSelectionsSub;
}
$bundleOptions = $bundleSub;
//echo '<pre>'; print_r($bundleOptions); exit;
try{
$_product->setCanSaveCustomOptions ( true );
$_product->setCanSaveBundleSelections ( true );
$_product->setAffectBundleProductSelections ( true );
$_product->setBundleOptionsData ( $bundleOptions );
$_product->setBundleSelectionsData ( $bundleSelections );
$_product->save();
}catch ( Exception $e ) {
Mage::log ( $e->getMessage () );
echo $e->getMessage ();
}
echo 1; exit;
$_product = null;
}
But this gives me following error as
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`aero_dev`.`catalog_product_bundle_option_value`, CONSTRAINT `FK_CAT_PRD_BNDL_OPT_VAL_OPT_ID_CAT_PRD_BNDL_OPT_OPT_ID` FOREIGN KEY (`option_id`) REFERENCES `catalog_product_bundle_option` (`opt), query was: INSERT INTO `catalog_product_bundle_option_value` (`option_id`, `store_id`, `title`) VALUES (?, ?, ?)
Any help would be appreciated.
I could not get it working using above approach so I tried to write custom query to put bundle items in the existing bundle product. When I looked into db I found there are basically 3 tables involved to create bundle items. These are
catalog_product_bundle_option
catalog_product_bundle_option_value
catalog_product_bundle_selection
I went through these tables and tried to looked for what magento puts If I create bundle items from magento admin.
So after some research I have done something like -
foreach( $csv as $key => $val ){
if( !isset($val['sku']) || empty($val['sku']) || $val['sku'] == '' ){
echo 'Not Valid Sku';
continue;
}
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',trim($val['sku']));
$_product->setCanSaveCustomOptions ( true );
$_product->setCanSaveBundleSelections ( true );
$_product->setAffectBundleProductSelections ( true );
$opt = $val['bundle_options'];
$optArr = explode(':', $opt);
//get the db write connection
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$connection->beginTransaction();
foreach ( $optArr as $key1 => $val1 ) {
$valTemp = explode( '(', $val1 );
$title = trim($valTemp[0]);
//insert into catalog_product_bundle_option with parent product id and type
$__fields = array();
$__fields['parent_id'] = $_product->getId();
$__fields['required'] = 1;
$__fields['type'] = 'select';
$__fields['position'] = $key1+1;
$connection->insert($catalog_product_bundle_option, $__fields);
$opt_id = $connection->lastInsertId();
$connection->commit();
//inert into catalog_product_bundle_option_value with option id, store id, title
$__fields = array();
$__fields['option_id'] = $opt_id;
$__fields['store_id'] = 0;
$__fields['title'] = $title;
$connection->insert($catalog_product_bundle_option_value, $__fields);
$val_id = $connection->lastInsertId();
$connection->commit();
$skuStr = trim($valTemp[1]);
$skuStrTemp = explode( ')', $skuStr );
$skuStr = trim($skuStrTemp[0]);
$skuTemp = explode( '+', $skuStr );
$pos = 1;
foreach( $skuTemp as $key2 => $val2 ){
$id = Mage::getModel('catalog/product')->getResource()->getIdBySku($val2);
//insert into catalog_product_bundle_selection with option_id, parent product id, product id, position, is_default, selection_price_type, selection_price_value, selection_qty, selection_can_change_qty
$__fields = array();
$__fields['option_id'] = $opt_id;
$__fields['parent_product_id'] = $_product->getId();
$__fields['product_id'] = $id;
$__fields['position'] = $pos + 1;
$__fields['selection_price_type'] = 0;
$__fields['selection_price_value'] = 10;
$__fields['selection_qty'] = 1;
$__fields['selection_can_change_qty'] = 0;
$connection->insert($catalog_product_bundle_selection, $__fields);
$connection->commit();
$pos++;
}
}
//update product
$_product->save();
$_product = null;
}
my csv contains 2 columns one is sku and another is bundle options
example - sku - 12345678
bundle options - item01(ZIPLOCK18X24+ZIPLOCK16X20):item02(ZIPLOCK14X20+XEROMOCR84208X11)
in which item01 is the option title followed by simple products sku ZIPLOCK18X24, ZIPLOCK16X20 and : seperated incase of multiple options title.
I hope it may help someone.

Resources