laravel-json-api / laravel

JSON:API for Laravel applications
MIT License
541 stars 41 forks source link

StoreContract in showRelated method of controller #210

Open ale1981 opened 2 years ago

ale1981 commented 2 years ago

Is there an easier way of me accessing the Store from within my custom readingRelatedx method without overriding the showRelated method in the controller and passing it in like this;

I need to override the data that is returned.

        if (method_exists($this, $hook = 'readingRelated' . Str::classify($fieldName))) {
            $response = $this->{$hook}($model, $request, $store);
        }
lindyhopchris commented 2 years ago

Sorry, I'm not totally sure what you're trying to do. Why access the store? The store is already used by the controller action to get the data.

If you need to access the data that is returned from the store, then that is accessible in the readRelated hook on the controller. That hook receives the data returned by the store as the second argument - see the docs here: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading

ale1981 commented 2 years ago

Hi @lindyhopchris, thanks for the response.

I am using the ReadingRelated method to override the response from cache, is there a better way of doing this?

    public function readingRelatedCustomerPrices(Customer $customer, CustomerPriceCollectionQuery $query, StoreContract $store)
    {
        $cacheKey = md5(request()->fullUrl());

        $data = Cache::remember($cacheKey, 300, function() use ($store, $customer, $query) {
            return $store->queryToMany(
                'customers',
                $customer,
                'customer-prices'
            )->withRequest($query)->getOrPaginate($query->page());
        });      

        return RelatedResponse::make(
            $customer,
            'customer-prices',
            $data,
        )->withQueryParameters($query);        
    }
lindyhopchris commented 2 years ago

Yeah a controller isn't really the right place for this - I'd expect caching to be a middleware concern.