Include model relationships in json response using Eloquent and Laravel 5

Include model relationships in json response using Eloquent and Laravel 5

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Mapping Relationships to Attributes in JSON Responses

When serializing Eloquent models for a REST API, you often encounter a situation where your database schema doesn't perfectly align with the data structure your frontend expects. Consider a scenario where the uploads table stores a foreign key integer—let's call it mime_id—referencing a row in a mimes table. That referenced row contains a string column, type, holding values like "image/jpeg".

When you return the model as JSON, Eloquent defaults to exposing the primary keys from related models or omitting them entirely depending on your configuration. In this specific case, the relationship is defined as:

public function mime() {
    return $this->hasOne('App\Models\Mime', 'mime');
}

However, the resulting JSON output looks like this:

{
    "serverPath": "upload/2015/06/06/21/filename.jpg",
    "filename": "filename.jpg",
    "mime": 92
}

The client receives the integer 92 (the ID of the related record) instead of the desired string "image/jpeg". You want to transform that relationship into an attribute that carries the specific data payload you need.

To achieve this, you should leverage Eloquent's appends property combined with a custom accessor. The appends array tells the JSON encoder to include these attributes in the output even if they don't exist directly on the model instance. However, simply listing the relationship name won't work because mime currently resolves to an instance of the Mime model, not the string you want.

You need to bridge the gap between the relationship and the serialized attribute. This is best handled by creating a custom accessor method that follows the naming convention defined in your $appends array.

In your Upload model, define the appendable attribute and implement the logic to fetch the related data:

protected $appends = ['mime_type'];

public function getMimeTypeAttribute($value) {
    // The relationship is named 'mime', so we access the relation here.
    // We assume the relationship name matches the accessor suffix.
    if ($this->relationLoaded('mime')) {
        return $this->mime->type;
    }

    // Handle cases where the relationship hasn't been loaded yet.
    // This prevents unnecessary database queries when fetching a single model.
    return $this->load('mime')->mime->type ?? null;
}

There is a subtle but important detail here: the method name must match the attribute name in the $appends array exactly, excluding the "get" and "Attribute" parts if you are using the standard accessor pattern. If your append is mime_type, the method should be getMimeTypeAttribute.

The code above checks whether the relationship has already been loaded via Eager Loading. This is a crucial optimization. If you fetch a collection of uploads with Upload::with('mime')->get(), the relationship exists in memory, and accessing $this->relationLoaded('mime') returns true, allowing you to return the value immediately without triggering a second query. Conversely, if you retrieve a single model without eager loading the relation, the accessor falls back to load('mime') to fetch the data on demand.

Alternatively, if you prefer not to use $appends, you can override the default JSON serialization behavior entirely by implementing the JsonSerializable interface in your model:

public function jsonSerialize(): array
{
    $array = parent::jsonSerialize();

    // Remove the raw ID from the output
    unset($array['mime']);

    // Append the formatted type string
    if ($this->relationLoaded('mime')) {
        $array['mime'] = $this->mime->type;
    } else {
        $array['mime'] = $this->load('mime')->mime->type ?? null;
    }

    return $array;
}

This approach gives you explicit control over every field returned, ensuring the foreign key integer never leaks into your API response. It also allows you to easily exclude timestamps or other sensitive fields that might be present in the default $attributes array.

Both methods effectively transform the internal database structure into a clean API contract. The choice between using $appends and overriding jsonSerialize() often comes down to how much control you need over the final payload and whether you want to maintain a separation of concerns between model attributes and presentation logic.

Our network