stream_get_contents in loop work half the time - image

In my controller I retrieve several boxes, and for the images of each box I do like this because I have the images in a blob column:
$donnees = $entityManager
->getRepository(Occasion::class)
->findBy(['isOnLine' => true], ['id' => "DESC"]);
$occasions = $paginator->paginate(
$donnees, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
12 /*limit per page*/
);
//on va stocker les images
$images = [];
foreach($occasions as $key => $occasion) {
$images[$key] = stream_get_contents($occasion->getBoite()->getImageBlob());
}
But when I dump $images I only have 1 image out of 2...
CataloguesController.php on line 137:
array:4 [▼
0 => "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwM ▶"
1 => ""
2 => "/9j/4AAQSkZJRgABAQEAeAB4AAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwM ▶"
3 => ""
]
Do you know why ? Thanks
???

Related

laravel how to add price product variations in laravel cart session

this is taking more than i anticipated,
On my shopping cart app i'm able to add product to app cart session with no problem, But now i need to add product variations like (color, size, ... etc) for every product added to the cart, These variation can change to product price according to users selection on product details page.
The code that i have currently is working for me except that i can't add a list of variation for a single product i can only create one variation then the code is replacing it with new variation value.
This is my cart object when running {{print_r($cart)}}
App\Cart Object
(
[items] => Array
(
[27] => Array
(
[id] => 27
[name] => product with variation and colors
[slug] => iphone-pro13
[price] => 100
[prefix] => QAR
[qty] => 1
[poster] => /image/md/9964677a-c957-4510-9eb4-f41578c069b3
[subtotal] => 730
[quotable] => 0
[variations] => Array // these are the list of product variations
(
[16] => Array
(
[id] => 16
[var_name] => This is the variation
[var_price] => 365.00
[var_qty] => 1
[var_subtotal] => 365
[color_code] => #e6bf00
)
)
)
[12] => Array
(
[id] => 12
[name] => Dolore quis sunt reiciendis.
[slug] => iste-autem-beatae-eaque-natus-distinctio
[price] => 96.08
[prefix] => QAR
[qty] => 1
[poster] => /media/default/product-placeholder.jpg
[subtotal] => 350.692
[quotable] => 0
[variations] => Array // these are the list of product variations
(
[0] => Array
(
[var_name] => This is the variation 2
[var_price] => 335.00
[var_qty] => 1
[var_subtotal] => 365
[color_code] => #e6bf00
)
)
)
)
the is my cart.php class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart extends Model
{
public $items = null;
public $itemsCount = 0;
public $grandTotal = 0;
public $variations = null;
public function __Construct($oldCart = null) {
if($oldCart) {
$this->items = $oldCart->items;
$this->itemsCount = $oldCart->itemsCount;
$this->grandTotal = $oldCart->grandTotal;
$this->variations = $oldCart->variations;
}
}
public function add($product) {
if (isset($this->items)) {
if( array_key_exists($product->id, $this->items) ) {
$qty = $this->items[$product->id]['qty'] += $product->qty;
$subtotal = $qty * $product->price;
}else{
$qty = $product->qty;
$subtotal = $product->subtotal;
}
}else{
$qty = $product->qty;
$subtotal = $product->subtotal;
}
$item = [
'id' => $product->id,
'name' => $product->name,
'slug' => $product->slug,
'price' => $product->price,
'prefix' => $product->prefix,
'qty' => $qty,
'poster' => $product->poster,
'subtotal' => $subtotal,
'quotable' => $product->quotable,
];
$variations = [
'id' => $product->variation_id,
'var_name' => $product->variation,
'var_price' => $product->variation_price,
'var_qty' => $qty,
'var_subtotal' => $qty * $product->variation_price,
'color_code' => $product->color,
];
$this->items[$product->id] = $item; // <-- this adds new product
$this->items[$product->id]['variations'][$product->variation_id] = $variations; // <-- this adds new product variation
$this->itemsCount +=1;
$this->grandTotal += $product->price * $product->qty;
}
}
Not sure where my code went wrong but i need to be able to add list of product variations instead of replacing current ones.
any ideas?

Laravel Excel Row Validation with conditions depends on another field input

I need to validate every rows from excel user upload in laravel which already converted to numeric array.
The validation i wanted is :
to make sure that the 1st field (0) is not blank,
then check whether the input is 'PRODUCTION-PROJECT' or not, if yes, then the 2nd field is required (1).
how to achieve this ?
My Controller Import class
$file = $request->file('file');
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setLoadSheetsOnly(['Upload']);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file->getRealPath());
$sheet = $spreadsheet->getActiveSheet();
$array = $sheet->toArray();
The array looks like this :
array:8 [
0 => array:11 [
0 => "PRODUCTION-PROJECT"
1 => "Consumable equipment expenses"
2 => "2022-07"
3 => "2022-08"
4 => "Forstr"
5 => "DOMESTIC"
6 => "ABCDE"
7 => "IDR"
8 => 2000
9 => 1
10 => "Enim temporibus est quis."
],
1 => array:11 [
0 => "PRODUCTION-PROJECT"
1 => null
2 => "2022-08"
3 => "2022-08"
4 => "RX"
5 => "DOMESTIC"
6 => "FGHIJ"
7 => "USD"
8 => 2000
9 => 1
10 => null
],
];
The validation i've tried so far like so :
$validatedData = Validator::make($array, [
'*.0' => 'required',
'*.1' => Rule::requiredIf('*.0' === 'PRODUCTION-PROJECT')
];
and the validation didn't show any error
The params of Rule::requiredIf should be a callback function that you need to custom the rule and input.
It's better to change Rule::requiredIf('*.0' === 'PRODUCTION-PROJECT') to 'required_if:*.0,PRODUCTION-PROJECT"'
so the correct code is :
$validatedData = Validator::make($array, [
'*.0' => 'required',
'*.1' => 'required_if:*.0,PRODUCTION-PROJECT'
];

Sum collection variables

i have the next collection:
It is grouped by zone and fundo and I need to sum all the sup_ha that each fundo contains
$transporFundo = $tansporCollect->groupBy(['zona','fundo']);
foreach ($transporFundo as $fundo) {
$supFundo = $fundo->sum('sup_ha');
dd($supFundo);
}
that is to say that for example of my collection for zona 1 and fundo 805 I would have to add the sup_ha field of the 364 records that are seen.
I tried to do it but I don't know how to access the field, as seen in my code I tried and it returns 0.
I hope you can help me, thanks
**
UPDATE
**
ok, remove the group by, for example show a collection like the following, the original has 700k of records
Illuminate\Support\Collection {#778646 ▼
#items: array:4 [▼
0 => array:3 [▼
"zona" => 1
"sup_ha" => 20
"fundo" => 805
]
1 => array:3 [▼
"zona" => 1
"sup_ha" => 10
"fundo" => 805
]
2 => array:3 [▼
"zona" => 2
"sup_ha" => 5
"fundo" => 800
]
3 => array:3 [▼
"zona" => 2
"sup_ha" => 10
"fundo" => 900
]
]
}
so, I need the sum of the sup_ha of equal fundo, like this:
fundo | sum
805 | 30
800 | 5
900 | 10
And I need the sum of the sup_ha of equal zona, like this:
zona | sum
1 | 30
2 | 15
Given this, that's why I had made a group by to calculate the sum of the fundo's. so now I don't know whether to think if it was right to do it like this
I hope you have clarified
Assuming your collection is assigned as $collection
$zonaArray = [];
$fundoArray = [];
$sum = 0;
foreach ($collection as $key => $t) {
if (!in_array($t['zona'], $zonaArray)) {
$zonaArray[$key]['zona'] = $t['zona'];
$zonaArray[$key]['sum'] = (float) $t['sup_ha'];
} else {
$zonaArray[$key]['sum'] = (float) $t['sup_ha'];
}
if (!in_array($t['fundo'], $fundoArray)) {
$fundoArray[$key]['fundo'] = $t['fundo'];
$fundoArray[$key]['sum'] = (float) $t['sup_ha'];
} else {
$fundoArray[$key]['sum'] = (float) $t['sup_ha'];
}
}
$checkzona = [];
$value = 0;
$finalZone = [];
$i = 0;
foreach ($zonaArray as $key => $val) {
if (in_array($val['zona'], $checkzona)) {
unset($finalZone[$i - 1]);
$val['sum'] = $value + (float) $val['sum'];
$finalZone[$i] = $val;
$i++;
} else {
$checkzona[] = $val['zona'];
$value = $val['sum'];
$finalZone[$i] = $val;
$i++;
}
}
Your zone wise sum output is looking like below.
array:2 [▼
1 => array:2 [▼
"zona" => 1
"sum" => 30.0
]
3 => array:2 [▼
"zona" => 2
"sum" => 15.0
]
]
For fundo sum:
$checkfundo = [];
$valuefundo = 0;
$finalFundo = [];
$k = 0;
foreach ($fundoArray as $key => $fundo) {
if (in_array($fundo['fundo'], $checkfundo)) {
unset($finalFundo[$k - 1]);
$fundo['sum'] = $valuefundo + (float) $fundo['sum'];
$finalFundo[$k] = $fundo;
$k++;
} else {
$checkfundo[] = $fundo['fundo'];
$valuefundo = $fundo['sum'];
$finalFundo[$k] = $fundo;
$k++;
}
}
Your fundo wise sum output is looking like below.
array:3 [▼
1 => array:2 [▼
"fundo" => 805
"sum" => 30.0
]
2 => array:2 [▼
"fundo" => 800
"sum" => 5.0
]
3 => array:2 [▼
"fundo" => 900
"sum" => 10.0
]
]
I hope it's working for you.
Assuming your collection is assigned to $collection.
so, I need the sum of the sup_ha of equal fundo.
High order functions
return $collection->groupBy('fundo')->map->sum('sup_ha');
Alternative
return $collection
->groupBy('fundo')
->transform(function (Collection $sub) {
return $sub->sum('sup_ha');
});
It prints
{
"805": 30,
"800": 5,
"900": 10
}
And I need the sum of the sup_ha of equal zona
High order functions
return $collection->groupBy('zona')->map->sum('sup_ha');
Alternative
return $collection
->groupBy('zona')
->transform(function (Collection $sub) {
return $sub->sum('sup_ha');
});
It prints
{
"1": 30,
"2": 15
}

Convert an array of array onto Collection Laravel

I have an array of array which results from several sql requests.
First I make a sql request in a foreach in order to have all the datas i need
foreach ($users as $user) {
// Two different Eloquent requests
$todo = User::select().....where('users.id' = $id);
$done = User::select().....where('users.id' = $id);
// I have operation on Collection that work fine ...
$totalTimes = $todo->toBase()->sum('dureeformation') ;
$spendTimes = $done->toBase()->sum('dureeformation') ;
$remainingTimes = $totalTimes - $spendTimes;
$all[] = ['user_id' => $id, 'totalTime' => $totalTimes, 'spendTime' => $spendTimes,'remainingTime' => $remainingTimes ];
}
My issue is the following... Outside the foreach i display the values and i have this array of array ...
array:16 [▼
0 => array:4 [▼
"user_id" => 1
"totalTime" => 465
"spendTime" => 0
"remainingTime" => 465
]
1 => array:4 [▼
"user_id" => 3
"totalTime" => 375
"spendTime" => 0
"remainingTime" => 375
]
I would need to have a Collection instead ... I tried to make $all = Collect(....) but i doesn't give me the expected result.
I need a collection because i have to create a Collection with this created collection and another one from another request.
Concerning this part i already had this case and i can solve it.
Thanks for your help
try this helper function :
$collection = collect($all);
This function will convert your array to collection.

Accessing image property of K2 item

I'm developing a module that displays a specific number of k2 items based on its category id. I can get those item but I'm not able to access the image on it. When I try $item->image returns the following notice:
Notice: Undefined property: stdClass::$image
Here is the object I get from my sql query:
stdClass Object
(
[id] => 5
[title] => News test item
[alias] => news-test-item
[catid] => 4
[published] => 1
[introtext] => Some intro text
[fulltext] =>
[video] =>
[gallery] =>
[extra_fields] => []
[extra_fields_search] =>
[created] => 2014-03-28 21:42:01
[created_by] => 252
[created_by_alias] =>
[checked_out] => 0
[checked_out_time] => 0000-00-00 00:00:00
[modified] => 0000-00-00 00:00:00
[modified_by] => 0
[publish_up] => 2014-03-28 21:42:01
[publish_down] => 0000-00-00 00:00:00
[trash] => 0
[access] => 1
[ordering] => 1
[featured] => 0
[featured_ordering] => 0
[image_caption] =>
[image_credits] =>
[video_caption] =>
[video_credits] =>
[hits] => 0
[params] => {"catItemTitle":"","catItemTitleLinked":"","catItemFeaturedNotice":"","catItemAuthor":"","catItemDateCreated":"","catItemRating":"","catItemImage":"","catItemIntroText":"","catItemExtraFields":"","catItemHits":"","catItemCategory":"","catItemTags":"","catItemAttachments":"","catItemAttachmentsCounter":"","catItemVideo":"","catItemVideoWidth":"","catItemVideoHeight":"","catItemAudioWidth":"","catItemAudioHeight":"","catItemVideoAutoPlay":"","catItemImageGallery":"","catItemDateModified":"","catItemReadMore":"","catItemCommentsAnchor":"","catItemK2Plugins":"","itemDateCreated":"","itemTitle":"","itemFeaturedNotice":"","itemAuthor":"","itemFontResizer":"","itemPrintButton":"","itemEmailButton":"","itemSocialButton":"","itemVideoAnchor":"","itemImageGalleryAnchor":"","itemCommentsAnchor":"","itemRating":"","itemImage":"","itemImgSize":"","itemImageMainCaption":"","itemImageMainCredits":"","itemIntroText":"","itemFullText":"","itemExtraFields":"","itemDateModified":"","itemHits":"","itemCategory":"","itemTags":"","itemAttachments":"","itemAttachmentsCounter":"","itemVideo":"","itemVideoWidth":"","itemVideoHeight":"","itemAudioWidth":"","itemAudioHeight":"","itemVideoAutoPlay":"","itemVideoCaption":"","itemVideoCredits":"","itemImageGallery":"","itemNavigation":"","itemComments":"","itemTwitterButton":"","itemFacebookButton":"","itemGooglePlusOneButton":"","itemAuthorBlock":"","itemAuthorImage":"","itemAuthorDescription":"","itemAuthorURL":"","itemAuthorEmail":"","itemAuthorLatest":"","itemAuthorLatestLimit":"","itemRelated":"","itemRelatedLimit":"","itemRelatedTitle":"","itemRelatedCategory":"","itemRelatedImageSize":"","itemRelatedIntrotext":"","itemRelatedFulltext":"","itemRelatedAuthor":"","itemRelatedMedia":"","itemRelatedImageGallery":"","itemK2Plugins":""}
[metadesc] =>
[metadata] => robots=
author=
[metakey] =>
[plugins] =>
[language] => *
[categoryname] => News-test
[categoryid] => 4
[categoryalias] => news-test
[categoryparams] => {"inheritFrom":"0","theme":"","num_leading_items":"2","num_leading_columns":"1","leadingImgSize":"Large","num_primary_items":"4","num_primary_columns":"2","primaryImgSize":"Medium","num_secondary_items":"4","num_secondary_columns":"1","secondaryImgSize":"Small","num_links":"4","num_links_columns":"1","linksImgSize":"XSmall","catCatalogMode":"0","catFeaturedItems":"1","catOrdering":"","catPagination":"2","catPaginationResults":"1","catTitle":"1","catTitleItemCounter":"1","catDescription":"1","catImage":"1","catFeedLink":"1","catFeedIcon":"1","subCategories":"1","subCatColumns":"2","subCatOrdering":"","subCatTitle":"1","subCatTitleItemCounter":"1","subCatDescription":"1","subCatImage":"1","itemImageXS":"","itemImageS":"","itemImageM":"","itemImageL":"","itemImageXL":"","catItemTitle":"1","catItemTitleLinked":"1","catItemFeaturedNotice":"0","catItemAuthor":"1","catItemDateCreated":"1","catItemRating":"0","catItemImage":"1","catItemIntroText":"1","catItemIntroTextWordLimit":"","catItemExtraFields":"0","catItemHits":"0","catItemCategory":"1","catItemTags":"1","catItemAttachments":"0","catItemAttachmentsCounter":"0","catItemVideo":"0","catItemVideoWidth":"","catItemVideoHeight":"","catItemAudioWidth":"","catItemAudioHeight":"","catItemVideoAutoPlay":"0","catItemImageGallery":"0","catItemDateModified":"0","catItemReadMore":"1","catItemCommentsAnchor":"1","catItemK2Plugins":"1","itemDateCreated":"1","itemTitle":"1","itemFeaturedNotice":"1","itemAuthor":"1","itemFontResizer":"1","itemPrintButton":"1","itemEmailButton":"1","itemSocialButton":"1","itemVideoAnchor":"1","itemImageGalleryAnchor":"1","itemCommentsAnchor":"1","itemRating":"1","itemImage":"1","itemImgSize":"Large","itemImageMainCaption":"1","itemImageMainCredits":"1","itemIntroText":"1","itemFullText":"1","itemExtraFields":"1","itemDateModified":"1","itemHits":"1","itemCategory":"1","itemTags":"1","itemAttachments":"1","itemAttachmentsCounter":"1","itemVideo":"1","itemVideoWidth":"","itemVideoHeight":"","itemAudioWidth":"","itemAudioHeight":"","itemVideoAutoPlay":"0","itemVideoCaption":"1","itemVideoCredits":"1","itemImageGallery":"1","itemNavigation":"1","itemComments":"1","itemTwitterButton":"1","itemFacebookButton":"1","itemGooglePlusOneButton":"1","itemAuthorBlock":"1","itemAuthorImage":"1","itemAuthorDescription":"1","itemAuthorURL":"1","itemAuthorEmail":"0","itemAuthorLatest":"1","itemAuthorLatestLimit":"5","itemRelated":"1","itemRelatedLimit":"5","itemRelatedTitle":"1","itemRelatedCategory":"0","itemRelatedImageSize":"0","itemRelatedIntrotext":"0","itemRelatedFulltext":"0","itemRelatedAuthor":"0","itemRelatedMedia":"0","itemRelatedImageGallery":"0","itemK2Plugins":"1","catMetaDesc":"","catMetaKey":"","catMetaRobots":"","catMetaAuthor":""}
)
What am I missing here?
Any help will be appreciated.
Edit: I'm using Joomla v2.5.18 and K2 v2.6.8
This is how K2 Content module adds the image to the item Object (taken from mod_k2_content/helper.php):
//Images
if ($params->get('itemImage'))
{
$date = JFactory::getDate($item->modified);
$timestamp = '?t='.$date->toUnix();
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_XS.jpg'))
{
$item->imageXSmall = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_XS.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageXSmall .= $timestamp;
}
}
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_S.jpg'))
{
$item->imageSmall = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_S.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageSmall .= $timestamp;
}
}
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_M.jpg'))
{
$item->imageMedium = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_M.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageMedium .= $timestamp;
}
}
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_L.jpg'))
{
$item->imageLarge = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_L.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageLarge .= $timestamp;
}
}
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_XL.jpg'))
{
$item->imageXLarge = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_XL.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageXLarge .= $timestamp;
}
}
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_Generic.jpg'))
{
$item->imageGeneric = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_Generic.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageGeneric .= $timestamp;
}
}
$image = 'image'.$params->get('itemImgSize', 'Small');
if (isset($item->$image))
$item->image = $item->$image;
}
You should have everything you need, otherwise take a look at the K2 Content module.
You didn't mention which Joomla and K2 versions you are using.
For Joomla > 1.6 You should parse the "params" property like this:
$params = new JRegistry($item->params);
And get the image as follows
J 1.6 <=> J 2.5.14
$params->getValue('itemImage')
J >= 2.5.14
$params->get('itemImage')
Reference: http://api.joomla.org/cms-3/classes/JRegistry.html

Resources