Skip to content

Instantly share code, notes, and snippets.

@taulutwashi
Created August 29, 2018 10:26
Show Gist options
  • Save taulutwashi/d1e97eca24f76b231dbb98f4370de913 to your computer and use it in GitHub Desktop.
Save taulutwashi/d1e97eca24f76b231dbb98f4370de913 to your computer and use it in GitHub Desktop.
laravel parent child in same table
class ProjectTree extends Model {
//each category might have one parent
public function parent() {
return $this->belongsToOne(static::class, 'parent_id');
}
//each category might have multiple children
public function children() {
return $this->hasMany(static::class, 'parent_id')->orderBy('name', 'asc');
}
}
$ProjectTree = ProjectTree::where('id',$id)->with([
'children'=>function($query){
$query->with([
'children'=>function($query){
$query->with(['children'=> function($query){
$query->with('children');
}]);
}]);
}])->select(['id'])->get();
<ul>
@foreach ($categories as $parent)
<li>{{ $parent->cat_name }}
@if ($parent->children->count())
<ul>
@foreach ($parent->children as $child)
<li>{{ $child->cat_name }}</li>
@endforeach
</ul>
@endif
</li>
@endforeach
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment