Level 60
@kalimeromk https://laracasts.com/discuss/channels/eloquent/category-tree here is one stupid solution, recursive query
Or read about https://en.wikipedia.org/wiki/Nested_set_model or use cache
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
@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("— ", $level) . $language->name, '</option>';
generateTree($language->children, $level + 1);
} else {
echo '<option>', str_repeat("— ", $level) . $language->name . '</option>';
}
}
}
@endphp
<select>
@php generateTree($languages) @endphp
</select>

Please or to participate in this conversation.