KalimeroMK's avatar

Nested category depth

My table's fields are:

id | name | parent_id

model

public function parent() { return $this->belongsTo('Category', 'parent_id'); }

public function children()
{
    return $this->hasMany('Category', 'parent_id');
}

save working ok but how to show them in select drop down withe detps leke this

--- Php
------ Laravel
--------- Version
------------ V 5.7
--- Python
------ Django
--- Ruby
0 likes
3 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

@kalimeromk hope it helps :)

Schema::create('languages', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->bigInteger('parent_id')->nullable();
});
Route::get('/', function () {
    // cache them if you don't change the often
    // you could even put them in local storage of the browser
    $languages = App\Language::with('children')->where('parent_id', 0)->get();

    return view('languages', compact('languages'));
});
@php
    function generateTree($languages, $level = 0)
    {
        foreach ($languages as $language) {
            if (count($language->children)) {
                echo '<option>', str_repeat("&mdash; ", $level) . $language->name, '</option>';
                generateTree($language->children, $level + 1);
            } else {
                echo '<option>', str_repeat("&mdash; ", $level) . $language->name . '</option>';
            }
        }
    }
@endphp

<select>
    @php generateTree($languages) @endphp
</select>

Please or to participate in this conversation.