stancl/virtualcolumn
stancl/virtualcolumn adds database-like “virtual columns” to Eloquent models, letting you define computed attributes that can be queried, sorted, and indexed as if they were real fields. Useful for JSON data, derived values, and cleaner, faster queries.
Begin by installing the package via Composer: composer require stancl/virtualcolumn. Next, include the HasVirtualColumns trait in any Eloquent model where you want to define computed attributes. Define virtual columns using the virtualColumns() method—return an array mapping keys (attribute names) to closures that accept the model instance and return computed values. The simplest use case is exposing a full name from first/last name fields on a User model, e.g., 'full_name' => fn($user) => $user->first_name . ' ' . $user->last_name.
virtualColumns() to avoid repeating code in resources or controllers.toArray() and toJson() to automatically serialize virtual columns alongside real attributes—ideal for API responses.withCount() or eager-loaded relations inside the closure).select()—they’re resolved at runtime. Use them for presentation or final-level logic, not for SQL WHERE/ORDER BY.getAttribute('virtual_attr') behavior.toArray()/toJson() by default, but use $appends = ['virtual_attr'] if you want them always included—even in non-resource contexts.VirtualColumn class or use a custom resolver if you need more advanced behavior (e.g., caching, lazy-loading, or type-casting).How can I help you explore Laravel packages today?