Tighten.co: Extending Models in Eloquent
On the Tighten.co blog there's a new tutorial posted by Caleb Porzio showing you how to correctly extend Eloquent models in a Laravel application.
When starting out with Eloquent, it’s natural to reach for familiar operations like where and join. For more advanced users, features like scopes, accessors, and mutators offer more expressive alternatives to the query-building patterns of old.Let’s explore another alternative that can be used as a stand-in for repetitive where statements and local scopes. This technique involves creating new Eloquent models that extend other models. By extending another model, you inherit the full functionality of the parent model, while retaining the ability to add custom methods, scopes, event listeners, etc. This is commonly referred to as “Single Table Inheritance,” but I prefer to just call it “Model Inheritance”.
He starts with an example using the User
model and creating a "local scope" method to answer the "is admin?" question. He then abstracts this out even more with an Admin
model that extends the User
that can be used instead to refer to admin users only. He includes examples of this in use for notifications, guard classes and model factories. He ends the post with one "gotcha" to this method - the fact that relationships no longer work on the Admin
model - and how to work around it.