i\'m currently working with Laravel and I\'m struggling with the fact that every model needs to extend from Eloquent and I\'m not sure how to implement a model Hierarchy
I found a bug (feature?) where Laravel 5 looks up the incorrect class if ParentClass and ChildClass have the same $table string. So if you call ParentClass::all() in certain situations it can return ChildClass instances in the collection!!
The Alpha's answer led me to a workaround where you create the following class structure:
abstract class BaseClass extends BaseModel
{
// ParentClass member variables and functions go here, to be shared between parent and child classes
}
class ParentClass extends BaseClass
{
protected $table = 'your_table';
// place no other member variables or functions in this class
}
class ChildClass extends BaseClass
{
protected $table = 'your_table';
// ChildClass member variables and functions go here
}
This seems to force Laravel to do the correct lookup when you call ParentClass::all() or ChildClass::all() since their common ancestor doesn't have a table declared. Just treat BaseObject as ParentObject and that way you don't have to muddy your inheritance concept with database details that shouldn't be relevant. I have not stress-tested this thoroughly yet, so be sure to note the reason for this class's existence in your code for future debugging breadcrumbs.