LadyDeathKZN's avatar

Skip non-object error

Hi everyone, before any says to check the logs etc, I know what the error is. The problem is that I am pulling data from a remote SQL database, and the product image will not always be available thus why it is throwing the below error: Trying to get property 'meta_value' of non-object.

// Get Product Image in WPStorage

                            $productImage = DB::table('postmeta')->where('post_id', $productThumbnail->meta_value)->where('meta_key', '_wp_attached_file')->first();
// Show image
<img src="{{Config::get('wp_url')}}/wp-content/uploads/{{!empty($productImage->meta_value)}}" alt="product_image" width="150px">

Is there any way I can bypass the above error? The _wp_attached_file is usually the uploaded product image, but if one is not available it defaults to a system one that is sitting in another table.

0 likes
2 replies
squibby's avatar

You can throw an error if the productImage is not found and then handle it however you want.

productImage = DB::table('postmeta')->where('post_id', $productThumbnail->meta_value)->where('meta_key', '_wp_attached_file')->firstOrFail();

Or you could do something conditional perhaps?

<img src="{{Config::get('wp_url')}}/wp-content/uploads/{{ $productImage->meta_value ??  'notfound.jpg'}}" alt="product_image" width="150px">

Or

@if($productImage)
<img src="{{Config::get('wp_url')}}/wp-content/uploads/{{!empty($productImage->meta_value)}}" alt="product_image" width="150px">
@else 
// something else
@endif
LadyDeathKZN's avatar

Hi @squibby thank you so much for the reply, unfortunately firstOrDie is only available on Eloquent. I also tried added a custom macro to the AppServiceProvider Boot, but that didn't work well lol.

Thank you for the other suggestions, I found the issue thanks to your help.

// Get Product Thumbnail
$productThumbnail = DB::table('postmeta')->where('post_id', $orderProductId->meta_value)->where('meta_key', '_thumbnail_id')->first();

// Get Product Image in Storage
 if(!empty($productThumbnail)) {
    $productImage = DB::table('postmeta')->where('post_id', $productThumbnail->meta_value)->where('meta_key', '_wp_attached_file')->first();
}

Please or to participate in this conversation.