Skip to content

Pivot model translations #426

@Dezmonter

Description

@Dezmonter

I create models: Clinic, Service, ClinicService (pivot) + ClinicServiceTranslable

Clinic model

class Clinic extends Model
{
    use HasFactory, Translatable;

    protected $fillable = [
        'is_active',
    ];

    public $translatedAttributes = [
        'name',
    ];

    public function services(): belongsToMany
    {
        return $this->belongsToMany(Service::class)
        ->withPivot('price');
    }
}

Service Model

class Service extends Model
{
    use HasFactory, Translatable;

    protected $fillable = [
        'is_active'
    ];

    public $translatedAttributes = [
        'name',
    ];

    protected function casts(): array
    {
        return [
            'is_active'               => 'boolean',
        ];
    }

    public function clinics(): BelongsToMany
    {
        return $this->belongsToMany(Clinic::class)
        ->withPivot('price');
    }
}

ClinicService Model

class ClinicService extends Pivot implements TranslatableContract
{
    use HasFactory, Translatable;

    protected $translationForeignKey = 'clinic_service_id';

    public $incrementing = true;

    protected $fillable = [
        'clinic_id',
        'service_id',
        'price',
    ];

    public $translatedAttributes = [
        'comment',
    ];    
}

ClinicServiceTranslable Model

class ClinicServiceTranslation extends Model
{
    public $timestamps = false;

    protected $fillable = [
        'comment',
    ];
}

I write connections in the controller

 $clinic = Clinic::WithTranslation()->with(['services' => fn ($query) => $query->withTranslation()])->get();

 return response()->json($clinic);

and I get the response:

{
    "id": 8,
    "city_id": 2,
    "is_active": true,
    "name": "TestClinic",
    "translations": [
        {
            "clinic_id": 8,
            "locale": 'ru',
            "name": "TestClinic",
        }
    ],
    "services": [
        {
            "id": 80,
            "is_active": true,
            "name": "ServiceName",
            "pivot": {
                "clinic_id": 8,
                "service_id": 80,
                "price": "682.5000",
            },
            "translations": [
                {
                "service_id": 80,
                "locale": 'uk'',
                "name": "ServiceName",
                }
            ]
        },
    ]
}

Help me get comment from pivot translable model clinic_service_translation...
In the end I want to get this pivot responce:

"pivot": {
    "clinic_id": 8,
    "service_id": 80,
    "comment": TESTCOMMENT
    "price": "682.5000",
},

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions