Skip to content

Instantly share code, notes, and snippets.

@tilhom
Created November 4, 2018 10:05
Show Gist options
  • Save tilhom/63b405a777df06dd3045f683892f3138 to your computer and use it in GitHub Desktop.
Save tilhom/63b405a777df06dd3045f683892f3138 to your computer and use it in GitHub Desktop.
laravel realization parent&child relation
<?php
class Category extends Model {
//each category might have one parent
public function parent() {
return $this->belongsToOne(static::class, 'cat_parent_id');
}
//each category might have multiple children
public function children() {
return $this->hasMany(static::class, 'cat_parent_id')->orderBy('cat_name', 'asc');
}
}
view()->composer('partials.header', function($view) {
$view->with('categories', Category::with('children')->whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->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