Skip to content

Instantly share code, notes, and snippets.

@joaorbrandao
Last active October 26, 2023 14:27
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save joaorbrandao/f23c8e4cdf776a2dfe7fd1f75f64f15e to your computer and use it in GitHub Desktop.
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;
}
}
@TheRealThor
Copy link

Oi João, how would the parent() look like if we allow multiple parents? Would it just be a change to belongsToMany?

@sergiog95
Copy link

Oi João, how would the parent() look like if we allow multiple parents? Would it just be a change to belongsToMany?

I think the root() method wouldn't work if parent() relation has changed to a belongsToMany.

@4m1nb4kh71
Copy link

Hi , i tried to use this trait , the parent and the children functions work perfectly , but the root function gives me an error
"Call to undefined method App\Models\Category::addEagerConstraints() "

@Mutembeijoe
Copy link

Hi , i tried to use this trait , the parent and the children functions work perfectly , but the root function gives me an error
"Call to undefined method App\Models\Category::addEagerConstraints() "

You need to call it like this $model->root() not like $model->with('root');

@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