Home > Net >  Laravel - Relationship With Resources and whenLoaded Not Working
Laravel - Relationship With Resources and whenLoaded Not Working

Time:11-03

So I am trying to control output utilizing resources as I was told it's the best way to model the data for api output.

Customer Model

 public function invoices () {
        return $this->hasMany('\App\Models\Invoice');
    }

Invoice Model:

public function customer() {
        return $this->belongsTo('\App\Models\Customer');
    }

Customer Resource:

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'invoices' => InvoiceResource::collection('invoices')
        ];
    }

Invoice Resource:

public function toArray($request)
{
    $customer = $this->whenLoaded('customer');
    return [
      'id' => $this->id,
      'customer' => CustomerResource::collection($this->whenLoaded($customer)),
    ];
}

Customer Controller:

public function index()
    {
        $customers = Customer::with(['invoices']);
        return CustomerResource::collection($customers->paginate(50))->response();
    }

But when I go to the API EndPoint

Error
Call to a member function first() on string

Illuminate\Http\Resources\Json\ResourceCollection::collectResource
vendor/laravel/framework/src/Illuminate/Http/Resources/CollectsResources.php:30

Error Starts in Stack from: return CustomerResource::collection($customers->paginate(50))->response();

CodePudding user response:

I had two issues 1st issue Invoice Resource:

public function toArray($request)
{
    $customer = $this->whenLoaded('customer');
    return [
      'id' => $this->id,
      'customer' => CustomerResource::collection($this->whenLoaded($customer)),
    ];
}

needed to be

{
    $customer = $this->whenLoaded('customer');
    return [
      'id' => $this->id,
      'customer' => CustomerResource::collection($this->whenLoaded($customer)),
    ];
}

Second Customer Rsource:

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'invoices' => InvoiceResource::collection('invoices')
        ];
    }

needed to be

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'invoices' => InvoiceResource::collection($this->whenLoaded('invoices'))
        ];
    }

CodePudding user response:

Each Invoice has only one Customer, right? so:

'customer' => new CustomerResource($this->whenLoaded('customer')),

Also what is $ sign before customer??

  • Related