Как исправить 'Свойство [id] не существует в этом экземпляре коллекции.' Когда я передаю параметр в Api Resource? - PullRequest
0 голосов
/ 17 января 2020

Здравствуйте, у меня сложная проблема, основанная на этом решении , мне удалось передать параметр в мой ресурс API, но перед передачей параметра я мог получить свой идентификатор с $this->id, теперь я ' получаю эту ошибку:

'Свойство [id] не существует в этом экземпляре коллекции.'

Вот как я отправлял свой запрос на ресурс API:

Контроллер:

return SellerRepresentativeResources::collection($representative);

Ресурс API:

public function toArray($request)
{
    return [
        'id' => $this->id
    ];
}

В приведенном выше методе я не нужно было передавать параметр, теперь основано на верхнем решении. Вот методы, которые я пробовал:

Контроллер:

$representative = Representatives::where('distributor_id', $request->distributor_id)->latest()->get();

    // I've got `"Method Illuminate\\Support\\Collection::product does not exist."` when i used below method
    return SellerRepresentativeResources::collection($representative)->product($request->product_id);

    // in this method i could access my product_id with $this->product_id but still i can't get my $this-id
    return SellerRepresentativeResources::make($representative)->product($request->product_id);

    //in this method i could access my product_id with $this->product_id but still i can't get my $this-id
    return (new SellerRepresentativeResources($representative))->product($request->product_id);

Ресурс API:

class SellerRepresentativeResources extends Resource
{
    protected $product;

    public function product($value){
        $this->product = $value;
        return $this;
    }

    // when i use $this->id i'm getting above error
    public function toArray($request)
    {
        return [
            'id' => $this->id
        ];
    }

    // when i use `parent...` i'm getting passed data from query not $prodcut.
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

Причина, по которой я пытаюсь передать параметр, состоит в том, что параметр, который я пытался отправить, используется для некоторых других запросов, которые я пытаюсь заставить его работать на основе product_id и некоторых других результатов. проверьте код ниже, который работает, когда я использую ->first(), но, как вы знаете, я получаю один результат с ->first().

    $representative = Representatives::where([
        ['state_id', auth()->user()->detail->state_id],
        ['distributor_id', $request->distributor_id]
    ])->first();

    if ($representative != null) {

        $generated = !! $representative->generate->where(
            'representative_id', $representative->id
        )->where(
            'marketer_id', auth()->id()
        )->count();



        if ($generated) {
            $requestItem = $representative->generate->where('marketer_id',auth()->id())->first();
            $requestItemArray = array(
                'id' => $requestItem->id,
                'marketer_id' => $requestItem->id,
                'representative_id' => $requestItem->id,
                'path' => $requestItem->path
            );
            $requestList = GeneretaedStateCentralRequestItemsResource::collection($requestItem->items);

            $checkExistItem = $representative->generate->where(
                'representative_id', $representative->id
            )->where(
                'marketer_id', auth()->id()
            )->first();

            $checkProductItem = !! MarketersRepresentativeRequestItems::where(
                'representative_request_id', $checkExistItem->id
            )->where(
                'product_id', $request->product_id
            )->count();

            if ($checkProductItem) {
                $getProdcutItem = MarketersRepresentativeRequestItems::where(
                    'representative_request_id', $checkExistItem->id
                )->where(
                    'product_id', $request->product_id
                )->first();
            }

        } else {

            $checkProductItem = false;
            $requestList = false;
            $requestItem = $representative->generate->where('marketer_id',auth()->id())->first();
            $checkRequestITem = !! $requestItem;
            if ($checkRequestITem) {
                $requestItemArray = array(
                    'id' => $requestItem->id,
                    'marketer_id' => $requestItem->id,
                    'representative_id' => $requestItem->id,
                    'path' => $requestItem->path
                );
            } else {
                $requestItemArray = null;
            }
        }

        if ($checkProductItem)
        {
            $representativeArray = array([
                'id' => $representative->id,
                'address' => $representative->address,
                'phone' => $representative->phone,
                'town_name' => $representative->town->name,
                'generated' => $representative,
                'checkProduct' => $checkProductItem,
                'items' => $requestList,
                'productDetail' => $getProdcutItem,
                'request_item' => $requestItemArray,
                'detailAlert' => false
            ]);
        } else {
            $representativeArray = array([
                'id' => $representative->id,
                'address' => $representative->address,
                'phone' => $representative->phone,
                'town_name' => $representative->town->name,
                'generated' => $generated,
                'items' => $requestList,
                'checkProduct' => $checkProductItem,
                'request_item' => $requestItemArray,
                'detailAlert' => false
            ]);
        }

        return SellerRepresentativeResources::collection($representativeArray);

    }
    else {
        return response(['message' => 'NoData'],Response::HTTP_ACCEPTED);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...