Search code examples
laraveleloquentlaravel-8eloquent-relationship

Laravel eloquent relation to json as string (only one attribute)


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?


Solution

  • 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;
    }