Carondimonio
Carondimonio

Reputation: 71

How to correctly extend a Laravel model?

I am fairly new to Laravel Eloquent way to handle models.

I need to create a base Product class with some common properties and relations and some other classes that have some other properties not in common.

I'll try to make a quick example: all products have a "serial_number", a "ship_date" etc...

But only the Bottle and the Bulb classes have a "glass_type" feature, while the Chair class have another one.

I am doing some

   abstract class Product extends Model {}
   class Bottle extends Product {}

but I think this way the Product doesn't have any attached db $table, and I don't know how to handle the migrations table and the logic behind.

What is the best method to apply here?

Thank you in advance

Upvotes: 2

Views: 3191

Answers (2)

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

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';

}

Upvotes: 2

Fabio
Fabio

Reputation: 1

We have partially "solved" this by including all needed fields in the product model. In addition we have introduced a Type field ("glass","Chair") and created different getter methods.

Other than this you can use the more elegant method described here, an store each type in a separate table: Extending Eloquent Models in Laravel (use different tables)

Upvotes: -1

Related Questions