Laravel 5.3 cannot use select value from collection - php

Im trying to calculate the price including tax of a product in an ecommerce app. In table tax i have the following columns:
id - iso_code - vat.
My query to obtain vat information for a particular countryid:
$taxRate = DB::table('tax')
->select('vat')
->where('iso_code', $productcountryid)
->get();
If I print_r the $taxRate value I obtain
Illuminate\Support\Collection Object ( [items:protected]
=> Array ( [0] => stdClass Object ( [vat] => 1 ) ) )
To retrieve vat value I used:
$taxRates=$taxRate[0]['tax'];
and I obtain the following info:
Cannot use object of type stdClass as array
On the other hand, using
$taxRates = $taxRate->vat;
Error: Undefined property: Illuminate\Support\Collection::$vat
My idea is to use $taxRate value to obtain a simple calculation
priceamount = $productprice * $taxRate
UPDATE using #assada suggestion ------
$array = $taxRate->toArray();
(array)[0]['vat']
gives error:
Cannot use object of type stdClass as array
any help appreciated about how to process the value returned in a collection.
brgds.

https://laravel.com/docs/5.4/collections
You can use some like this:
$taxRate = DB::table('tax')
->select('vat')
->where('iso_code', $productcountryid)
->get();
$collection = collect($taxRate);
$array = $collection->toArray();
or just try
$taxRate = DB::table('tax')
->select('vat')
->where('iso_code', $productcountryid)
->get();
$array = $taxRate->toArray();

Related

Laravel / Mongodb - Remove specifc object form array of objects

I have this array ( matching_competitors ) of objects in mongodb:
I want to delete specific object where id_product_competitor value is match.
For example I want to delete object number 2 where id_product_compeitor = 224731
To do that I am using this query :
$delete_to_mongodb = DB::connection('mongodb')
->collection( 'products_' . $id_project)
->where('id', $id_user_product )
->where( 'matching_competitors.id_product_competitor', $product_id )
->unset( 'matching_competitors.$.id_product_competitor');
But the specific object is not deleting :(

query laravel not working if pass variable in Where NOT IN

I'm trying to filter items from a database table
what I do is get the ids that I want to exclude and then through -> whereNotIn in laravel, I pass the ids
$idcontracts=array();
$idbike=array();
$biciCorretta = array();
$findcontract=Contract::whereRaw('? between data_inizio and data_fine', [$datainizio])->whereRaw('? between data_inizio and data_fine', [$datafine])->get();
foreach ($findcontract as $key) {
if (!in_array($key->id,$idcontracts)) {
array_push($idcontracts,$key->id);
}
}
foreach ($idcontracts as $idcontract) {
$bike_contracts=DB::table('bike_contract')->where('contract_id',$idcontract)->get();
foreach ($bike_contracts as $bike_contract) {
if (!in_array($bike_contract->bike_id,$idbike)) {
array_push($idbike,$bike_contract->bike_id);
}
}
}
$notid=implode("', '",$idbike);
up to this point I have no problem.
the result of "implode" gives me the ids I want to remove
this is the result of $idbike and $notid:
this is the query I write to exclude the ids found:
$bikes = Bike::with('category')->whereNotIn('id', [$notid])->orderBy('category_id')->get();
the problem is that it doesn't exclude me the ids passed with $notid
but if I manually pass the ids, it removes them instead:
$bikes = Bike::with('category')->whereNotIn('id', [40,41,34,36,39])->orderBy('category_id')->get();
am I doing something wrong?
You shouldn't implode $notid, that makes it a string and Laravels whereNotIn() already does that for you.
->whereNotIn('id', $idbike)
And remove the $notid parameter, as it is not needed.
implode will return in string, and because of that it will not work correctly, you should pass it as array instead.
If you print data
$idbike =[40,41,34,36,39];
print_r($idbike);
Output will be Array
Array
(
[0] => 40
[1] => 41
[2] => 34
[3] => 36
[4] => 39
)
and if you print below code
$notid=[implode(",",$idbike)];
print_r($notid);
The output will be
Array
(
[0] => 40,41,34,36,39
)
So your query become
->whereNotIn('id', ["40,41,34,36,39"])
so laravel searching for id of "40,41,34,36,39". so its not returning result
So you can pass array directly to wherenotin
->whereNotIn('id', $idbike)
Laravel, whereNotIn method removes elements from the collection that have a specified item value that is contained within the given array. That means you have to pass an array
So, idbike is the array you mentioned
$bikes = Bike::with('category')->whereNotIn('id', idbike)->orderBy('category_id')->get();

Get the single element from the array

I got the following array (the array is retrieved through a db query). Now, my question is, how do I get a single element like e_domains from the array mentioned below:
stdClass Object
(
[id] => 1
[uni_origin] => Aachen
[e_domains] => rwth-aachen.de
)
I got the output shown above by running the following line of codes:
if ($results ) {
foreach ( $results as $result ){
echo'<pre>'; print_r($result) ;
}
}
First off, that's not an array, that's an object. Like it says: "stdClass Object".
Access object properties like this:
$object->property_name
In your case, it would be:
$result->e_domains
There are much more to learn on the subject, like static properties, visibility etc. In your case, the above example will work.
Read more about classes and objects in the manual: http://php.net/manual/en/language.oop5.basic.php
Try this:
$e_domains = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
Hope it helpt.

PHP - adding an object with its properties to array

I have a problem with modifying an array.
foreach ($page->getResults() as $lineItem) {
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
}
This code gives a result:
Array
(
[0] => Google\AdsApi\Dfp\v201611\Location Object
(
[id:protected] => 2250
[type:protected] => COUNTRY
[canonicalParentId:protected] =>
[displayName:protected] => France
)
)
I'm trying to add another, [1] , same type of object to this array.
I made a class to create and add an object:
class Location{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$location = new Location();
$location->createProperty('id', '2792');
$location->createProperty('type', 'COUNTRY');
$location->createProperty('canonicalParentId', '');
$location->createProperty('displayName', 'Turkey');
array_push($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations(), $location);
Then, if I pass this into print_r() function
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
It shows the same result.
In the end, I need to send this updated whole $lineItem to this function
$lineItems = $lineItemService->updateLineItems(array($lineItem));
But seems like before sending I can't properly add an object to the array.
Thanks in advance.
PHP returns arrays as a value instead of as a reference. This means you must set the modified value back somehow.
Looking at the library apparently in question, there seems to be setExcludedLocations method for that purpose.
So your code should be something like:
$geo_targeting = $lineItem->getTargeting()->getGeoTargeting();
$excluded_locations = $geo_targeting->getExcludedLocations();
array_push($excluded_locations, $location);
$geo_targeting->setExcludedLocations($excluded_locations);

How to read data from an array containing object within him

Im having a hard time to read some data that i get from joomla 2.5. First i have created a module that stores data on DB as a json. So first i read from DB linke:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('params')));
$query->from($db->quoteName('#__modules'));
$query->where($db->quoteName('module') . ' = '. $db->quote('mod_products'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
and the result that i get as an array that contain objects, and each object has json data.
below is the arrray that i get from the query:
Array
(
[0] => stdClass Object
(
[params] => {
"product_name":"Sangiovese",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"1"
}
)
[1] => stdClass Object
(
[params] => {
"product_name":"Syrah",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"0",
}
)
[2] => stdClass Object
(
[params] => {
"product_name":"Merlot",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"0"
}
)
[3] => stdClass Object
(
[params] => {
"product_name":"Vermentino",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"White",
"isvisible":"0"
}
)
);
So what i want to do is to access the data within each param for examle:
PS: Array name is $results.
,
EX: i want to access product_name of each of the products that are on this array, or subtitle and so on.
so i did something like this, but its not working, i know i am not doing it right, but i hope someone can help me, and i would really appruciate it.
foreach( $results as $result )
{
echo $result->prams->product_name;
}
Error that shows when this code gets executed:
Notice: Trying to get property of non-object in
I really would need some advice on this.
Thank you!
Every item in your list is an object:
[0] => stdClass Object
[1] => stdClass Object
And every object has a params property which is a string containing JSON data.
You need to use json_decode built-in function to convert JSON string to an object or array.
Try this approach:
$paramsDecoded = json_decode($result->params, true);
print $paramsDecoded['product_name'];
Hello and thanks to all who helped,
I managed to make it functional.
So im gonna post here all the code for everyone else that passes on the same waters and needs help.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('params')));
$query->from($db->quoteName('#__modules'));
$query->where($db->quoteName('module') . ' = '. $db->quote('mod_products') .' AND '. $db->quoteName('language') . ' <> '. $db->quote('en-GB'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
$count = count($results);
What i did to make the functionality i needed:
for ($i=0; $i < $count; $i++) {
$json = $results[$i]->params;
$product = json_decode($json);
// code here, example
echo $product->product_subtitle;
}
So, yes. I needed to decode using json_decode first, before using it on other parts of the code.
Thanks for helping. Hope this posts helps other developers who same as me, will have difficulties working with the way Joomla manipulates objects stored in database.

Categories