Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent relationships with Extended Models

I'm working on a site that has extended Models, eg.

class Asset extends Model {

  public function project() {
    return $this->belongsTo(Project::class);
  }
}

class Video extends Asset {

}

Do I need to establish the same belongsTo Eloquent relationship with the extended class, or by virtue of the parent class having it, will Laravel do the rest?

Additionally, is there any documentation anywhere that goes into detail about how to structure such relationships (ie. in terms of Controllers)? I can't find anything on the (usually excellent) Laracasts website.

like image 599
Chuck Le Butt Avatar asked Oct 29 '22 06:10

Chuck Le Butt


1 Answers

You don't need to instance the extended method twice, unless you want to override it with a different behaviour.

I personally use a lot of inheritance in my applications, and it works just as you would expect, every relation keeps working and querying using the parent default values or the specific protected variables you declare.

For example, if you declare a protected $table = 'foo', the child will also take that variable to perform its query, or you could override it on the child to query a different table from the parent.

In terms of documentation, the reason you are not finding much information I think it's because this is more a PHP and OOP issue than a framework specific one.

If you want to declare polymorphic relations, which are a really common way to implement multiple inheritance in your SQL, Laravel has your back, with specific Eloquent relations and migration commands, like $table->morphs('asset');.

Hope this helps you.

like image 139
Asur Avatar answered Nov 15 '22 06:11

Asur