laraveleloquenteloquent-relationship

Laravel model embed nested model when just attribute appended


Need to append calculate attribute into model:

class Field extends Model {
//...
    protected $appends = ['typename'];
//...
    public function getTypenameAttribute(): string {
        return $this->type->name;
    }
}

Model dump shows me the following:

{
    "id": "9bc5b05b-46cf-470d-a848-cdb60aec2213",
    "name": "Показание термометра",
    "default": true,
    "twin_id": "9bc5b05b-3df3-4efd-8ce0-7a30be87af72",
    "type_id": "9bc3cea3-47e6-4ef2-a78f-347d51abbe3d",
    "created_at": "2024-04-10T07:21:36.000000Z",
    "updated_at": "2024-04-10T07:21:36.000000Z",
    "deleted_at": null,
    "origin": "thermo",
    "typename": "Целочисленное без знака",
    "type": {
      "id": "9bc3cea3-47e6-4ef2-a78f-347d51abbe3d",
      "name": "Целочисленное без знака",
      "influx_type": "uint",
      "created_at": "2024-04-09T08:54:37.000000Z",
      "updated_at": "2024-04-09T08:54:37.000000Z",
      "deleted_at": null
    }
  }

typename calculated ok. But I don't want to include nested type object. My model class not contain any $with, so this object completely unexpected.

How to exclude this nested object from dump?


Solution

  • Please make sure that you model relationship looks like something this

    class Field extends Model {
    // List of attributes to append to JSON serialization
    protected $appends = ['typename'];
    
    // List of attributes or relations to hide from JSON serialization
    protected $hidden = ['type'];
    
    // Getter for the appended attribute
    public function getTypenameAttribute(): string {
        return $this->type->name;
    }
    
    
    public function type() {
        return $this->belongsTo(Type::class, 'type_id');
    }
    

    }

    Usage

    $field = Field::find(1); //replace your id