How to Select Categories in Php Web App?

13-06-2017

Category table:

id adi url parent
1 Elektronik elektronik NULL
2 Laptop laptop 1

We can use following codes to extract parent->child category array:

/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $categories = DB::table('kategori as k1')
    ->join('kategori as k2', 'k1.id', '=', 'k2.parent')
    ->select('k1.adi as parent_adi', 'k1.url as parent_url', 'k2.adi as child_adi', 'k2.url as child_url')
    ->get();
    $parents = array();
    $parentNames = array();
    foreach ($categories as $category) {
        if (in_array($category->parent_adi, $parentNames)) continue;
        $parentNames[] = $category->parent_adi;
        $parents[] = array("adi" => $category->parent_adi, "url" => $category->parent_url);
    }
    $result = array();
    
    foreach ($parents as $parent) {
        $children = array();
        foreach ($categories as $category) {
            if ($parent["adi"] == $category->parent_adi) {
                $children[] = array("adi" => $category->child_adi, "url" => $category->child_url);
            }
        }
        $result[] = array("parent" => $parent, "children" => $children);
    }
    
    return view('client.index')->with("categories", $result);
}

index.blade.php page

<div class="collapse navbar-collapse" id="bs-megadropdown-tabs">
    <ul class="nav navbar-nav">
        <li class="active"><a href="home" class="act">Ana Sayfa</a></li>
        @foreach($categories as $category)
        <li class="dropdown">
            <a href="/{{$category["parent"]["url"]}}" class="dropdown-toggle"
                data-toggle="dropdown">{{$category["parent"]["adi"]}}
                <b class="caret"></b></a>
                    <ul class="dropdown-menu  columns-2">
                        <div class="row">
                            <div class="col-sm-3">
                                <ul class="multi-column-dropdown">
                                    @foreach($category["children"] as $child)
                                    <li><a href="/{{$child["url"]}}">{{$child["adi"]}}</a></li>
                                    @endforeach
                                </ul>
                            </div>
                        </div>
                    </ul>
                </li>
                @endforeach
                <li><a href="mail">İletişim</a></li>
            </ul>
        </div>

© 2019 All rights reserved. Codesenior.COM