Laravel: Remove an attribute in returned result

Laravel: Remove an attribute in returned result

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

Stefan Bogdanescu

Founder & Senior Architect

Filtering Appended Attributes in Laravel Collections

When returning a model collection from an API endpoint, you often encounter attributes that aren't persisted in the database. In the scenario described, qr_code_url is likely an accessor or a computed property derived from qr_code. While this approach adds flexibility to your data layer, it complicates serialization when you need to expose only specific fields to the client. The goal is to return a JSON response containing id and qr_code_url, effectively stripping out the raw file path (qr_code) without altering the underlying model structure or triggering database queries.

The most straightforward solution relies on transforming the collection before sending it back to the user. You can achieve this by mapping over the collection and explicitly constructing a new array for each item, excluding unwanted keys. This approach ensures that the original Eloquent models remain untouched in memory until the response is fully serialized, preserving the benefits of eager loading or lazy evaluation if they were configured elsewhere.

Here is how you can implement this using a map closure:

return Order::all()->map(function ($order) {
    return [
        'id' => $order->id,
        'qr_code_url' => $order->qr_code_url,
    ];
})->toJson();

This method creates a new array for every item in the collection. By explicitly listing only the attributes you wish to include, any appended properties like qr_code, as well as default Eloquent fields such as created_at or updated_at, are automatically omitted from the output. This is generally safer than trying to filter existing keys because it prevents accidental leakage of sensitive data that might exist in other columns on the model.

If you prefer a more concise syntax, Laravel's collection methods allow you to use array destructuring within the map closure:

return Order::all()->map(function ($order) {
    return [
        'id' => $order->id,
        'qr_code_url' => $order->qr_code_url,
    ];
})->toArray(); // or ->toJson() depending on your needs

Alternatively, if you are comfortable manipulating the array directly after retrieval but before returning it, you can use the only and except methods. However, these methods work on the attributes present in the model's attribute set. Since qr_code is a physical column or accessor defined in the model, except will successfully remove it from the serialized output if you pass the correct key names:

return Order::all()->toArray()->except(['qr_code']);

Note that calling toArray() converts the collection into a standard array of associative arrays. If qr_code is indeed an accessor and not a database column, removing it via except works because accessors are included in the default serialization list. However, this approach does not give you fine-grained control over which columns to keep versus which to exclude. If your requirement changes frequently or if you need to include only specific fields regardless of what exists on the model, the map approach is more robust.

A common pitfall with these methods is performance when dealing with large datasets. Mapping a collection creates a new array for every single item in memory. For small to medium collections (e.g., less than 1,000 items), this overhead is negligible. However, if you are paginating and processing thousands of records at once, consider ensuring you are only fetching the necessary columns using $orders = Order::select('id', 'qr_code')->get();. This reduces memory usage before the mapping logic even runs.

There is also a trade-off regarding data type safety. If qr_code_url relies on an accessor that modifies the value (e.g., appending a domain), accessing it inside the map closure ensures the transformation happens at the right time. If you access the attribute in a query scope or before mapping, ensure the context allows the accessor to run.

For teams looking to standardize this pattern across multiple controllers or API resources, consider creating a dedicated service class or an Eloquent Scope that handles the filtering logic centrally. This keeps your controllers clean and ensures consistency in how data is exposed to clients. For more advanced serialization needs, exploring packages like spatie/laravel-query-builder or configuring global JSON casts can offer additional abstraction layers.

Our network