laravelinheritanceeloquentextending-classes

Laravel - Extending Model


I've created a BaseModel class, which extends from Model. It seemed like everything was working fine, but now I've run into a problem when saving. I'm overriding the save() method in this BaseModel. I'd just like to add some attributes to the model before saving. So I do that, then call return parent::save($options);. The method signature is still the same: public function save(array $options = []).

It appears to be grabbing the name of the BaseModel class for the table name when performing the insert (it's using base_models as the table name), rather than the actual model that is being saved. Has anyone run into this before? What is the proper way of extending from the model class?

I originally created some traits to handle some extra functionality, but thought it would be a better idea to just create a base model and have my models extend from that instead.


Solution

  • In your model (the child one that extends the base model) add the table name explictly for example:

    class SomeChildModel extends BaseModel {
    
        // Manually set the table name
        protected $table = 'table_name';
    
    }