Laravel Trying to Get property of non object (from eloquent model) - php

Already read some of questions about this problem on stackoverflow and none of that answers apply to me.
When I run:
$item_price = ItemPrice::where('item_name',$itemname)->first();
and then
$item_price->price
I get Trying to get property of non-object but when I run:
dd($item_price = ItemPrice::where('item_name',$itemname)->first());
It's returning object with attributes name, price etc. I don't really understand what is happening here.
Full code:
foreach ($inventorydecoded->assets as $asset) {
$i = 0;
$a = 0;
while ($a < 1) {
if ($inventorydecoded->descriptions[$i]->classid == $asset->classid) {
$a = 1;
$classid = $inventorydecoded->descriptions[$i]->classid;
$itemname = $inventorydecoded->descriptions[$i]->market_hash_name;
$tradable = $inventorydecoded->descriptions[$i]->tradable;
$name_color = $inventorydecoded->descriptions[$i]->name_color;
;
}
$i++;
} // end of while
if ($tradable === 1 && strpos_arr($itemname, $blacklist) == false ) {
$item_price = ItemPrice::whereItemName($itemname)->first();
// dd(ItemPrice::where('item_name',$itemname)->first());
$items[] = ['assetid' => $asset->assetid,'classid'=> $classid,'itemname'=>$itemname,'name_color'=>$name_color,'price'=> $item_price->price];
$serialized_inventory = serialize($items);
}
} // end of foreach

You're using this query in loop, so one of those is empty and returns null. So you need to do simple check:
if (is_null($item_price)) {
// There is no price for this item, do something.
}

Try this:
$item_price = ItemPrice::whereItemName($itemname)->first();

Related

How to fix Array overwritten after foreach loop php

I am having issue data Array overwritten in foreach loop. Result I am getting like this wrongRight together .Right answer is showing but also wrong for example ZucchiniCauliflower.Please help
CODE 1
$data = array();
$dis_07= null;
$dis_03 = null;
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id = $value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$dis_07 = $value->category;
$dis_02 = $value->child_id;
}
if (isset($ccat_id) && $ccat_id == $id) {
$dis_03 = $value->category;
$dis_02 = $value->parent_id;
}
}
}
$data['Dis_03'] = $dis_03;
$data['Dis_07'] = $dis_07;
if (isset($data['Dis_03'])) {
echo $data['Dis_03'];
}
if (isset($data['Dis_07'])) {
echo $data['Dis_07'];
}
First I tried this way But In one I was getting right in second link I am getting right So Tried the code previous one .In the prvious I am getting correct and wrong one together EExample ZucchiniCauliflower
CODE 2
if (isset($id)) {
$db = Database::newInstance();
$data = array();
$data['cat_status'] = 1;
$sql = "SELECT * FROM category WHERE cat_status=:cat_status ";
$row = $db->read($sql,$data);
$data['id'] = $crypt->decryptId($id);
echo $data['id'];
$id=$data['id'];
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id=$value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$data['Dis_03']=$value->category;
}
if (isset($ccat_id) && $ccat_id == $id) {
$data['Dis_03'] = $value->category;
break;
}
}
}
}
--------------------------READ FROM HERE------------------------
Here is a link one when I click on this link
$id=$value11->gccat_id;
$title
I expected the output is
Home>Raspberry
Here is a link Second link when I click on this link
Here id is ($value11->gccat_id)
window.open('<?= BASEURL ?>ap/'+id,'_self');
I expected the output is
Home>Cauliflower
1. WHEN I Use the Code 2 (Added break in this condition
(isset($ccat_id) && $ccat_id == $id)) Then click on link second
it gives output Home>Cauliflower which I was expecting. It is
correct.
2. But this time as I added the break in (isset($ccat_id) && $ccat_id == $id). I click on link one It gives wrong output which I was not expecting. Home>Squash which is wrong.
In one link I was expecting
Home>Cauliflower
ERROR NOTE If I add Break; then link Second gives correct output but when I remove Break; then link one give correct. I wanted Both link should give correct output.
Problem was with cat_id,ccat_id ,gccat_id.
I provided 8 digit unique number with the following output,now I am getting the correct output.
function generateUniqueNumber() {
return sprintf('%08d', mt_rand(1, 99999999));
}

Undefined offset Error checking php

Im getting an undefined offset error. I know why i am getting the error and where it is. What i am trying to work out is how to implement the appropriate error checking to prevent this from happening. The method is currently being called via ajax and thus the error cause's issues with the return of any strings etc.
Following is the class's method being called, its variables are being set vie $_GET.
$id = $_GET['id'];
$product = $_GET['name'];
$price = $_GET['price'];
//check for existing product
for($i = 0; $i <= count($_SESSION['BASKET']); $i++) {
//if product exsits incrent by 1
if($_SESSION['BASKET'][$i]['id'] == $id){
$_SESSION['BASKET'][$i]['amount'] = $_SESSION['BASKET'][$i]['amount'] + 1;
break;
//if doesnt exsist creat product array
} else {
$item = array('id' => $id,'amount' => 1,'product' => $product,'price' => $price);
}
}
if(isset($item)){
//push product to session array
array_push($_SESSION['BASKET'], $item);
}
As you can see the method checks to see if the basket currently contains a product and updates by incrementing the quantity ('amount'). I have a constructer that creates the basket array in the class. The issue occurs when the $_SESSION['BASKET'] is called and is empty but still exists as in :
array (
)
this creates and undefined offset error when checking the id in the if statement as the array technically exists but the offset 0 does not. Any ideas how i can handle this?.
Code changes i a have made that cause the same error
if(isset($_SESSION['BASKET'][$i]) && $_SESSION['BASKET'][$i]['id'] == $id){
I have moved the logic outside the loop and added a bool variable, i can then query this to check if a item was found in the array. This allowed me to create another if statement to check if the sessions values were set rather than checking if the array was created.
$id = $_GET['id'];
$product = $_GET['name'];
$price = $_GET['price'];
$exsist = false;
//check for existing product
for($i = 0; $i <= count($_SESSION['BASKET']); $i++) {
if(isset($_SESSION['BASKET'][$i])){
//if product exsits incrent by 1
if(isset($_SESSION['BASKET'][$i]) && $_SESSION['BASKET'][$i]['id'] == $id){
$_SESSION['BASKET'][$i]['amount'] = $_SESSION['BASKET'][$i]['amount'] + 1;
$exsist = true;
break;
}
}
}
if($exsist != true){
$item = array('id' => $id,'amount' => 1,'product' => $product,'price' => $price);
array_push($_SESSION['BASKET'], $item);
}

debug_backtrace - long parameter

I have the following function:
function backtrace($Object=false)
{
$x = 0;
foreach((array)debug_backtrace($Object) as $aVal)
{
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}
But when I use it, I'm getting an error like below:
Warning: debug_backtrace() expects parameter 1 to be long, string given in /mypath/ on line 717 ---> foreach((array)debug_backtrace($Object) as $aVal)
What's causing the error? How can I fix it?
The first parameter of debug_backtrace() is a bitmask of options (i.e. a long). It is a simple boolean true/false in PHP versions prior to 5.3.6.
To fix it, either don't pass in the $Object variable you're currently passing in or update it to be any combination of the supported options that you want to be used.
Example:
$Object = DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT;
If you want to add a pre-condition to your current block of code that will set a default value if $Object is invalid, you could try something like:
function backtrace($Object = false) {
if (!is_long($Object) || (!($Object & DEBUG_BACKTRACE_PROVIDE_OBJECT) && !($Object & DEBUG_BACKTRACE_IGNORE_ARGS))) {
$Object = 0;
}
$x = 0;
foreach((array)debug_backtrace($Object) as $aVal) {
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}
for php >= 5.3.6, you should use bitmask options
function backtrace($Object=false) {
$x = 0;
foreach((array)debug_backtrace($Object ? DEBUG_BACKTRACE_PROVIDE_OBJECT : 0) as $aVal)
{
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}

PHP foreach loop JSON

I know there are like hundreds similar questions on this site, but I just can't get my code working...
I have this JSON
{
"version":"1.0.0",
"buildDate":20131029,
"buildTime":165127,
"lockPath":"..\\var\\lock",
"scriptPath":"..\\var\\lock",
"connections":
[
{
"name":"o016561",
"bez":"GEW-NRW",
"type":"OVPN"
},
{
"name":"o016482",
"bez":"GEW-BW",
"type":"OVPN"
},
{
"name":"o019998",
"bez":"GEW-SH",
"type":"OVPN"
}
]}
how can I access the "name" values to check if there's an existing file with an equal name?
I tried
$json_config_data = json_decode(file_get_contents($json_path,true));
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
}
else
{
$status = 0;
}
}
but I always get $status = 0...
I think there's an easy solution for this, but I'm pretty new to PHP so I'd be glad for any kind of help.
Thanks in advice
You're resetting the value of $status for every iteration which means that the last connection HAS to be the correct one. You're probably looking for a break statement.
$json_config_data = json_decode(file_get_contents($json_path,true));
$status = 0; //Default to 0
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
break; //End the loop
}
}
This would only result in $status == 1 if the final name matched your requirements; otherwise you're setting $status back to 0. You should break out of the loop when you find a match:
$status = 0;
foreach ($json_config_data->connections as $connectionName) {
if ($connectionName->name == $fileName) {
$status = 1;
break; // this breaks out of the foreach loop
}
}

Increment Shopping cart item quantity using session

I know that my question could be very similar to anothers in Stackoverflow. I have found some similar questions but actually I couldn't get the right solution for my problem;
I am writing shopping cart using Sessions and ajax-json.
My products
structure is a bit complicated. It has name, size, type, colour and a
specific price for each type and size. The main point is that I can't
increment the item quantity if the name, size, type, color and price are
the same, if I'm adding the same product. Here is my code. I think I
am writing right, but I can't understand what is the problem.
Actually it increments the item quantity, but just one time, and when
I am checking the array, it's item quantity has not been incremented.
$data = json_decode($_POST['jsonData'], true);
$pr_type = $data['pr_type'];
$pr_size = $data['pr_size'];
$pr_link = $data['pr_link'];
$pr_color = $data['pr_color'];
$pr_price = $data['pr_price'];
$products_s = $this->getSession()->get('prof_cart');
$product = array();
if (empty($products_s)) {
$products_s = array();
} else {
$products_s = $products_s;
}
$products = Model::factory('Client_Product')->getProductById($pr_link);
$type = Model::factory("Client_Product")->getProductTypeByLink($pr_type);
$size = Model::factory("Client_Product")->getProductSizeById($pr_size);
if ($pr_type != 'undefined') {
$product['type'] = $type[0]['title'];
} else {
$product['type'] = "";
}
$isCreate = true;
foreach ($products_s as $id) {
if ($id['price'] == $pr_price &&
$id['title'] == $products[0]['title'] &&
$id['size'] == $size[0]['size'] &&
$id['type'] == $type[0]['title']) {
$id['quant']++;
$isCreate = false;
}
}
if ($isCreate) {
$product['quant'] = 1;
$product['size'] = $size[0]['size'];
$product['title'] = $products[0]['title'];
$product['price'] = $pr_price;
$product['color'] = $pr_color;
array_push($products_s, $product);
}
$sum = 0;
foreach ($products_s as $id) {
$sum += $id['price'] * $id['quant'];
}
//echo $sum;
echo "<pre>";
var_dump($products_s);
echo "</pre>";
$this->getSession()->set('prof_cart', $products_s);
$this->getSession()->set('prof_sum', $sum);
You need to increase quantity in your main product array like below.
foreach ($products_s as $key => $id) {
if ($id['price'] == $pr_price &&
$id['title'] == $products[0]['title'] &&
$id['size'] == $size[0]['size'] &&
$id['type'] == $type[0]['title']) {
$products_s[$key]['quant']++;
$isCreate = false;
}
}
try this :
foreach ($products_s as $id) {
if ($id['price'] == $pr_price &&
$id['title'] == $products[0]['title'] &&
$id['size'] == $size[0]['size'] &&
$id['type'] == $type[0]['title']) {
$id['quant'] = $id['quant']++;
$isCreate = false;
}
}

Categories