Add a custom attribute to a Laravel / Eloquent model on load?

Add a custom attribute to a Laravel / Eloquent model on load?

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

Stefan Bogdanescu

Founder & Senior Architect

Adding Custom Attributes to Eloquent Models on Load

Transforming a standard collection of EventSession models into an API response that includes non-persisted data like an available flag is a common requirement. The pattern shown in your controller—iterating over the collection and appending properties manually—is functionally correct but introduces unnecessary overhead. By deferring the calculation or fetching logic until it is strictly necessary, you can keep your database queries lean and your controllers clean.

The most direct approach to attaching properties without iterating via a foreach loop is utilizing Eloquent's mass assignment features during hydration. When Eloquent loads a model from the database, it hydrates the attributes defined in the $fillable property or protected by accessors. However, for dynamic attributes that require business logic (like checking availability) rather than direct column mapping, you should leverage the getRelations() method combined with event listeners or, more simply, the getAttributes() scope within a relationship definition or an accessor pattern.

In this specific case, since $sessions is returned as JSON and the available property must be present in the final payload, you can attach it to the collection using the push method on the query builder or by utilizing a custom accessor if the logic is static. However, because available relies on $session->getAvailability(), which implies external logic, the cleanest integration point is often a custom accessor defined on the model itself, provided you can pass the necessary context.

If modifying the model class directly isn't an option due to architectural constraints, you can use Eloquent's event system. The eloquent.retrieved event fires after a model has been retrieved from the database but before it is returned to the application. You can listen for this event and attach the custom property directly to the model instance:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;

Event::listen('eloquent.retrieved:EventSession', function (Model $model) {
    $model->available = $model->getAvailability();
});

This approach removes the need for the loop in your controller. The index method becomes a simple query:

public function index()
{
    return EventSession::all();
}

When you call EventSession::all(), Eloquent hydrates each model, triggers the retrieval event, and populates the available property on every instance. Since you are returning the collection as JSON, the serializer will automatically include any public properties that exist on the model instance at the time of serialization, provided they don't violate mass assignment rules on the specific output format being used (like API resources).

Trade-offs and Pitfalls

While event listeners offer a global solution, they introduce a subtle coupling between your domain logic and the retrieval mechanism. If you later decide to switch from eager loading all models to fetching them individually or using scopes that bypass certain events, the custom attribute might not populate as expected. Furthermore, relying on events for data transformation can sometimes obscure where the data actually comes from, making debugging harder if the getAvailability() method throws an exception during hydration.

A more explicit alternative is defining a custom accessor in the model class:

class EventSession extends Model
{
    public function getAvailableAttribute()
    {
        return $this->getAvailability();
    }
}

In this scenario, you would access it as $session->available. However, note that accessors are typically used to transform database columns. Since available is not a column and requires logic that might depend on the specific state of the session (perhaps including other relationships), an accessor works if getAvailability() is purely a model method. If getAvailability() relies on external services or complex state, sticking to the event listener or a factory pattern might be safer.

Returning Data for JSON APIs

Since you are returning these models as part of an API response, ensure that your serialization strategy handles dynamic properties correctly. Standard Eloquent collections serialize all public properties. If you use Laravel's JsonResource classes, remember that they usually only serialize attributes defined in the $toArray method or explicitly included fields. In such cases, you must override the toArray method to include the available key:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'available' => $this->getAvailability(),
        // other fields...
    ];
}

This ensures that even if you populate the property via an event, it is explicitly included in the JSON output. This pattern maintains separation of concerns: the controller handles the query, the model (or resource) handles the transformation, and the API layer manages the serialization contract.

Our network