#Property won't print but shows in JSON object

32 messages · Page 1 of 1 (latest)

marsh fossil
#

We made a API Resource with a few properties. When we print the JSON object we can see all the properties. But whenever we want to print a specific property $object->property it won't show.

marsh fossil
#

Property won't print but shows in JSON object

radiant coral
#
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class SyncArticleResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request): array
    {
        $hasPurchaseArticle = $this->resource->relationLoaded('purchasearticle');

        return [
            'art_nr' => $this->art_nr,
            'art_naam' => $this->product->name,
            'art_adviesprijs' => $this->purchasearticle->art_adviesprijs,
            'art_verkoopprijs' => $this->art_verkoopprijs,
            'art_leverstatus' => $this->art_leverstatus,
            'art_vrd' => $this->when($this->purchasearticle, $this->purchasearticle->art_vrd),
            'properties' => ProductPropertyResource::collection($this->productproperties),
        ];
    }
}
#

I'm a colleague of TheRottenTomato 😋

long falcon
radiant coral
#

The $hasPurchaseArticle was used in one of the tests.

marsh fossil
#

So when we print this as JSON object we can see that every property has a value, but when we print the single property 'art_adviesprijs' it doesn't show any data.

mellow ginkgo
#

Share the code of you accessing and displaying the JSON data. If you see the data in your JSON object, you shouldn't have any problem accessing i.t

long falcon
long falcon
#

Hello? Earth to @marsh fossil and/or @radiant coral?

radiant coral
#
            $product_chunks = Article::orderBy('art_naam')
                ->whereIn('art_nr',$article_ids)
                ->chunk(100, function ($articlesToSyncRaw) use ($webshop_ids, $woo_product_ids, $wooSyncLibrary) {
                    $articlesToSync = SyncArticleResource::collection($articlesToSyncRaw);

                    //CREATE AS SYNC BATCH.
                    $update_batch = [];

                    foreach ($articlesToSync as $articleToSync) {
                        try {
                            //DETERMINE THE PRICES.
                            $sku = $articleToSync->art_nr;

                            //ONLY UPDATE IF THE PRODUCT EXISTS IN WOO.
                            if(isset($woo_product_ids[$sku]))
                            {
                                //GET THE WOO ID.
                                $woo_id = $woo_product_ids[$sku];

                                //GET THE PRICES.
                                $prices_array = ProductHelperLibrary::getProductPrices($articleToSync);
#

This where we call the productHelperLibrary with the article from a Resource

#
public static function getProductPrices($articleToSync) 
    {
        $recommended_price = $articleToSync->art_adviesprijs;
        $selling_price = $articleToSync->art_verkoopprijs;
        $supplier_status = $articleToSync->art_leverstatus;
        $sales_price = "";

        Log::info(json_encode($articleToSync));
        Log::info($articleToSync->art_naam.': Recommended price: '.$recommended_price.', Selling price: '.$selling_price.' , Stock: '.$articleToSync->art_vrd);

        //HAS A SELLING PRICE AND RECOMMENDED PRICE.
        if((!empty($selling_price) && floatval($selling_price) > 0) && (!empty($recommended_price) && floatval($recommended_price) > 0))
        {
            if(floatval($selling_price) < floatval($recommended_price))
            {
                $sales_price = $selling_price;
                $regular_price = $recommended_price;
                $price = $selling_price;
            }
            else
            {
                $sales_price = '';
                $regular_price = $recommended_price;
                $price = $recommended_price;
            }

            return [
                'regular_price' => $regular_price,
                'sale_price' => $sales_price,
                'price' => $price,
                'supplier_status' => $supplier_status,
                'stock' => $articleToSync->art_vrd
            ];
        }

        return false;
    }
#

This is the class where it happens

#

And one of the log entries which show the output of the json_encoded resource and the output of the attributes in the resource:

#

[2023-05-12 08:31:43] local.INFO: {"art_nr":196524,"art_naam":"Tonar Top Tip naaldreiniger","art_adviesprijs":16.4876,"art_verkoopprijs":20.6198,"art_leverstatus":"B","art_vrd":"7","properties":[{"id":"7","vid":"167"},{"id":"8","vid":null},{"id":"9","vid":null},{"id":"78","vid":"48604"},{"id":"1559","vid":"39780"},{"id":"1620","vid":"50016"},{"id":"1650","vid":"40658"},{"id":"1708","vid":null},{"id":"1784","vid":"49817"},{"id":"1846","vid":"51620"},{"id":"1856","vid":"53150"},{"id":"1986","vid":"57601"},{"id":"2140","vid":"60609"},{"id":"2141","vid":"60682"},{"id":"2142","vid":"60621"},{"id":"2143","vid":"60646"},{"id":"2159","vid":null}]}
[2023-05-12 08:31:43] local.INFO: Tonar Tip Top naaldreiniger: Recommended price: , Selling price: 20.6198 , Stock: 0

#

You can see that in the json it has a value and the attribute from the resource is empty.

radiant coral
#

When I convert the object to json and then back to an array the attributes are accessible:

#
$articleArray = json_decode(json_encode($articleToSync),true);
long falcon
radiant coral
#

That is the only way I currently can read the attribute. I all other cases it stays inaccessible

#

The table aswel as the related table both have the same name in another database. Maybe that is an issue but then I would expect it not to show up in the json either.

radiant coral
# long falcon What on earth are you doing?

In this way the object is converted to json and the json back to an array in which the attribute is available. Not the most sexy way but it is a workaround untill we find the root cause.

long falcon
marsh fossil
long falcon
# marsh fossil ```php $articlesToSyn = SyncArticleResource::collection($articlesToSyncRaw); ```...

So why are you converting an object to a resource, when you then just do more stuff? Just don’t wrap it in a resource, then you can do your foreach loops or whatever with the original data:

    $product_chunks = Article::orderBy('art_naam')
        ->whereIn('art_nr',$article_ids)
        ->chunk(100, function ($articlesToSyncRaw) use ($webshop_ids, $woo_product_ids, $wooSyncLibrary) {
--          $articlesToSync = SyncArticleResource::collection($articlesToSyncRaw);

            //CREATE AS SYNC BATCH.
            $update_batch = [];

--          foreach ($articlesToSync as $articleToSync) {
++          foreach ($articlesToSyncRaw as $article) {
                // Do stuff with $article
            }

You just seem to be making your life more difficult for the sake of it, by using resources incorrectly. A resource should be used to present data, at the end of a method. Not right at the start of it before you actually manipulate the data being presented.

public function someControllerAction()
{
    // Get data...

    // Manipulate data...

    // Present data...
    return SyncArticleResource::collection($manipulatedArticles);
}
radiant coral
#

I get your point but we wrapped it in a Resource to get a simpel model and not have a structure where the purchase article is a child of article.

#

We in fact created a structure which was already known to the organisation.

long falcon
#

If you want to create entity classes, then create entity classes. Don’t use things for purposes they’re not intended to be used, and then act confused when things don’t work properly.

radiant coral
#

Ok clear, but how would you do this in another way?