PHPackages                             phaza/single-table-inheritance - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. phaza/single-table-inheritance

ActiveLibrary[Database &amp; ORM](/categories/database)

phaza/single-table-inheritance
==============================

Single Table Inheritance Trait

1.0.1(10y ago)1515.8k2MITPHPPHP &gt;=5.4.0

Since Sep 15Pushed 10y ago4 watchersCompare

[ Source](https://github.com/phaza/single-table-inheritance)[ Packagist](https://packagist.org/packages/phaza/single-table-inheritance)[ RSS](/packages/phaza-single-table-inheritance/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (9)Used By (0)

Single Table Inheritance
========================

[](#single-table-inheritance)

Credit
======

[](#credit)

This code is a fork of [Nanigans/single-table-inheritance](https://github.com/Nanigans/single-table-inheritance). I've only updated it to work with Laravel 5

[![Latest Stable Version](https://camo.githubusercontent.com/db16e38b3d57666d00d1d268b31dcf13c01c38baa07266df3ddd0dc50668f8c8/68747470733a2f2f706f7365722e707567782e6f72672f7068617a612f73696e676c652d7461626c652d696e6865726974616e63652f762f737461626c652e737667)](https://packagist.org/packages/phaza/single-table-inheritance)[![Total Downloads](https://camo.githubusercontent.com/56191bb97e17973afd14d358766a36823baa2ae5688f94ab396436a79aea9ff1/68747470733a2f2f706f7365722e707567782e6f72672f7068617a612f73696e676c652d7461626c652d696e6865726974616e63652f646f776e6c6f6164732e737667)](https://packagist.org/packages/phaza/single-table-inheritance)[![Latest Unstable Version](https://camo.githubusercontent.com/4f905d118555e98566e1367d4c78ff4aef860692f972fbc07f6076119c35ec8e/68747470733a2f2f706f7365722e707567782e6f72672f7068617a612f73696e676c652d7461626c652d696e6865726974616e63652f762f756e737461626c652e737667)](https://packagist.org/packages/phaza/single-table-inheritance)[![License](https://camo.githubusercontent.com/6fedcc9d3c3b70d6bea3214c7d042287619ae8e6821dfcd42f6c1f8285cabe8f/68747470733a2f2f706f7365722e707567782e6f72672f7068617a612f73696e676c652d7461626c652d696e6865726974616e63652f6c6963656e73652e737667)](https://packagist.org/packages/phaza/single-table-inheritance)

Single Table Inheritance is a trait for Laravel 5.0.6+ Eloquent models that allows multiple models to be stored in the same database table. We support a few key featres

- Implemented as a Trait so that it plays nice with others, such as Laravel's `SoftDeletingTrait` or the excellent [Validating](https://github.com/dwightwatson/validating), without requiring a complicated mess of Eloquent Model subclasses.
- Allow arbitrary class hierarchies not just two-level parent-child relationships.
- Customizable database column name that is used to store the model type.
- Customizable string for the model type value stored in the database. (As opposed to forcing the use of the fully qualified model class name.)
- Allow database rows that don't map to known model types. They will never be returned in queries.

Installation
============

[](#installation)

Simply add the package to your `composer.json` file and run `composer update`.

```
"phaza/single-table-inheritance": "1.0.*"

```

Or go to your project directory where the `composer.json` file is located and type:

```
composer require "phaza/single-table-inheritance:1.0.*"
```

Overview
========

[](#overview)

Getting started with the Single Tabe Inheritance Trait is simple. Add the constraint and add a few properties to your models. A complete example of a `Vehicle` super class with two subclasses `Truck` and `Car` is given by

```
use Phaza\SingleTableInheritance\SingleTableInheritanceTrait;

class Vehicle extends Eloquent
{
  use SingleTableInheritanceTrait;

  protected $table = "vehicles";

  protected static $singleTableTypeField = 'type';

  protected static $singleTableSubclasses = ['Car', 'Truck'];
}

class Car extends Vehicle
{
  protected static $singleTableType = 'car';
}

class Truck extends Vehicle
{
  protected static $singleTableType = 'truck';
}
```

There are four requred properties to be defined in your classes:

### Define the database table

[](#define-the-database-table)

In the root model set the `protected` property `$table` to define which database table to use to store all your classes.
*Note:* even if you are using the default for the root class (i.e. the 'vehicles' table for the `Vehicle` class) this is required so that subclasses inherit the same setting rather than defaulting to their own table name.

### Define the databse column to store the class type

[](#define-the-databse-column-to-store-the-class-type)

In the root model set the `protected static` proerty `$singleTableTypeField` to define which database column to use to store the type of each class.

### Define the subclasses

[](#define-the-subclasses)

In the root model and each branch model define the `protected static` property `$singleTableSubclasses` to define which subclasses are part of the classes hierarchy.

### Define the values for class type

[](#define-the-values-for-class-type)

In each concrete class set the `protected static` property `$singleTableType` to define the string value for this class that will be stored in the `$singleTableTypeField` database column.

Multi Level Class Hierarchies
-----------------------------

[](#multi-level-class-hierarchies)

It's not uncommon to have many levels in your class hierarchy. Its easy to define that structure by declaring subclasses at each level. For example suppose you have a Vehicle super class with two subclasses Bike and MotorVehicle. MotorVehicle in trun has two subclasses Car and Truck. You would define the classes like this:

```
use Phaza\SingleTableInheritance\SingleTableInheritanceTrait;

class Vehicle extends Eloquent
{
  use SingleTableInheritanceTrait;

  protected $table = "vehicles";

  protected static $singleTableTypeField = 'type';

  protected static $singleTableSubclasses = ['MotorVehicle', 'Bike'];
}

class MotorVehicle extends Vehicle
{
  protected static $singleTableSubclasses = ['Car', 'Truck'];
}

class Car extends MotorVehicle
{
  protected static $singleTableType = 'car';
}

class Truck extends MotorVehicle
{
  protected static $singleTableType = 'truck';
}

class Bike extends Vehicle
{
  protected static $singleTableType = 'bike';
}
```

Defining Which Atttributes Are Persisted
----------------------------------------

[](#defining-which-atttributes-are-persisted)

Eloquent is extremly lenient in allowing you to get and set attributes. There is no mechanism to declare the set of attributes that a model supports. If you misues and attribute it typically results in a SQL error if you try to issue an insert or update for a column that doesn't exist. By default the SingleTableInheritanceTrait opperates the same way. However, when storing a class hierarchy in a single table there are often database columns that don't apply to all classes in the heirarchy. That Eloquent will store values in those columns makes it considerably easier to write bugs. There, the SingleTableInheritanceTrait allows you to define which attributes are persisted. The set of persisted attributes is also inherited from parent classes.

```
class Vehicle extends Eloquent
{
  protected static $persisted = ['color']
}

class MotorVehicle extends Vehicle
{
  protected static $persisted = ['fuel']
}
```

In the above example the class `Vehicle` would persiste the attribute `color` and the class `MotorVehicle` would persiste both `color` and `fuel`.

### Automatically Persisted Attributes

[](#automatically-persisted-attributes)

For convineience the model primary key and any dates are automatically added to the list of persisted attributes.

### BelongsTo Relations

[](#belongsto-relations)

If you are restricting the persisted attribute and yoru model has BelongsTo relations then you must include the foreign key column of the BelongsTo relation. For example:

```
class Vehicle extends Eloquent
{
  protected static $persisted = ['color', 'owner_id'];

  public function owner()
  {
    return $this->belongsTo('User', 'owner_id');
  }
}
```

Unfortunately there is no efficient way to automatically detect BelongsTo foreign keys.

### Throwing Exceptions for Invalid Attributes

[](#throwing-exceptions-for-invalid-attributes)

BY default the SingleTableINheritanceTrait will handle invalid attributes silently It ignores non-persisted attributes when a model is saved and ignores non-persisted columns when hydrating a model from a builder query. However, you can force exceptions to be thrown when invalid attributes are encounted in either situation by setting the `$throwInvalidAttributeExceptions` property to true.

```
/**
 * Whether the model should throw an InvalidAttributesException if non-persisted
 * attributes are encoutered when saving or hydrating a model.
 * If not set, it will default to false.
 *
 * @var boolean
 */
protected static $throwInvalidAttributeExceptions = true;
```

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~39 days

Recently: every ~68 days

Total

8

Last Release

3986d ago

Major Versions

0.4.1 → 1.0.02015-02-25

### Community

Maintainers

![](https://www.gravatar.com/avatar/3142b43984be5ecb8559c6ba874c1875a319dc6fd3e3c7f230d00e1cb958583c?d=identicon)[phaza](/maintainers/phaza)

---

Top Contributors

[![jonspalmer](https://avatars.githubusercontent.com/u/328224?v=4)](https://github.com/jonspalmer "jonspalmer (10 commits)")[![phaza](https://avatars.githubusercontent.com/u/4553?v=4)](https://github.com/phaza "phaza (4 commits)")[![reiz](https://avatars.githubusercontent.com/u/652130?v=4)](https://github.com/reiz "reiz (1 commits)")

---

Tags

laravelmodeleloquenttablesingleinheritance

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/phaza-single-table-inheritance/health.svg)

```
[![Health](https://phpackages.com/badges/phaza-single-table-inheritance/health.svg)](https://phpackages.com/packages/phaza-single-table-inheritance)
```

###  Alternatives

[nanigans/single-table-inheritance

Single Table Inheritance Trait

2512.5M3](/packages/nanigans-single-table-inheritance)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
