Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Atef95's avatar

Api Resource load pivot not working

Hey guys

I'm using API resource and I want to load data from pivot table

the issue that key is getting ignored

that's my code

Order.php

<?php

namespace App\Modules\Order\Models;

use App\Modules\Product\Models\Product;
use App\Modules\User\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Order extends Model
{
    protected $guarded = ['id'];
    protected $with = ['products.content', 'user'];

    use SoftDeletes;

    public function products()
    {
        return $this->belongsToMany(Product::class, 'order_products')->withPivot('unit','type','price')->withTimestamps();
    }
    public function user()
    {
        return $this->belongsTo(User::class);
    }

  

}

Product.php

<?php

namespace App\Modules\Product\Models;


use App\Modules\User\Models\User;
use App\Modules\Order\Models\Order;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    protected $guarded = ['id'];

    use SoftDeletes;

    public function content()
    {
        return $this->morphTo();
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'user_products')->withTimestamps();
    }

    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_products')->withPivot('unit','type','price')->withTimestamps();
    }


 


}

OrderResource Class

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\User as UserResource;

class Order extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'code' => $this->code,
            'status' => $this->status,
            'products' => $this->whenPivotLoaded('order_products', function() {
                return $this->pivot->unit;
            })
           
           
        ];
    }
}


I'm getting as a result below

  "orders": [
        {
            "id": 8,
            "code": "cldBExCWE4-1",
            "status": 1
        },
        {
            "id": 9,
            "code": "5mM6sUYWdd-9",
            "status": 2
        }
    ]

what is missing ?

0 likes
1 reply

Please or to participate in this conversation.