-2

When I serialize a model (e.g. ModelA) that has a relation (e.g. ModelB), it looks something like this:

[{
    "id": 1,
    "name": "model a1 name",
    "modelB": {
        "id": 1,
        "name": "model b1 name"
    }
}, {
    "id": 2,
    "name": "model a2 name",
    "modelB": {
        "id": 3,
        "name": "model b3 name"
    }
}, {
    "id": 3,
    "name": "model a3 name",
    "modelB": {
        "id": 2,
        "name": "model b2 name"
    }
}]

Instead I want to compress the relation since there's only one useful information to something like this:

[{
    "id": 1,
    "name": "model a1 name",
    "modelB": "model b1 name"
}, {
    "id: 2",
    "name": "model a2 name",
    "modelB": "model b3 name"
}, {
    "id": 3,
    "name": "model a3 name",
    "modelB": "model b2 name"
}]

This behavior however should only occur when it's serialized as a relation but not if it's the top-level model. Is it possible to configure that inside the relation instead of an accessor in the parent model or modifing the resulting collection afterwards?

shaedrich
  • 5,457
  • 3
  • 26
  • 42

1 Answers1

0

in your model1 overwrite the function called toArray and add custom your column something like this :

public function toArray()
{
    $array = parent::toArray();
    $array['modelB'] = $this->modelB()->first()->name;
    return $array;
}
iFahd Dev
  • 71
  • 1
  • 7
  • That works in general but that will do that even if the model is not a relation but a top-level model. In the latter case I don't wont this to happen. – shaedrich Apr 29 '21 at 14:26
  • add condition or use model resource – iFahd Dev Apr 29 '21 at 14:28
  • That's what I'm asking for: How do I know which case (condition) applies to the current invocation? How would I use a model resource in that case? – shaedrich Apr 29 '21 at 14:32
  • Oh, sorry. I misread your answer. You're right. Not exactly what I thought I might get but definitely something I can work with. Thank you! – shaedrich Apr 29 '21 at 14:40