Skip to content

Instantly share code, notes, and snippets.

@joaorbrandao
Last active September 13, 2024 19:02
Show Gist options
  • Select an option

  • Save joaorbrandao/f23c8e4cdf776a2dfe7fd1f75f64f15e to your computer and use it in GitHub Desktop.

Select an option

Save joaorbrandao/f23c8e4cdf776a2dfe7fd1f75f64f15e to your computer and use it in GitHub Desktop.
Laravel Model Self Reference
<?php
namespace App\Traits;
trait SelfReferenceTrait
{
protected $parentColumn = 'parent_id';
public function parent()
{
return $this->belongsTo(static::class);
}
public function children()
{
return $this->hasMany(static::class, $this->parentColumn);
}
public function allChildren()
{
return $this->children()->with('allChildren');
}
public function root()
{
return $this->parent
? $this->parent->root()
: $this;
}
}
@4m1nb4kh71
Copy link

Thank you sir, it works now, but only for one model instance .
Do you have any idea on how can i call it for all the model instances returned?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment