Created
November 4, 2018 10:05
-
-
Save tilhom/63b405a777df06dd3045f683892f3138 to your computer and use it in GitHub Desktop.
laravel realization parent&child relation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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