Back to Blog 2 min read

Creating BreadCrumbs In Parent-Child Relation

You may have worked on these kinds of projects or may not. But this small idea comes from a project where I was building a file-manager, Even though...

You may have worked on these kinds of projects or may not. But this small idea comes from a project where I was building a file-manager, Even though I'm working in my Full day job but I keep building side projects.

As a developer, I would love to give this advice never stop learning new things, it doesn't matter if you are in some other technologies or any other domain. What matter's is you are upskilling yourself. That's the most important thing to do.

In a few days I'll be starting a new blog series where I will share Reactjs blogs while building backend with PHP or Laravel. So, If you are a traditional developer that doesn't our hands still can operate over new trends.

Well, Let's come to the point.

Building BreadCrumb For Child Parent Relations

As I'm saying that I only have faced this kind of logic in my file-manager, so that's why lemme share a little bit about that.

Just imagine, In Filemanager I had a task to create folders, and also you can upload your files. And all of you also be having a filemanager in your mobile phone, It was not so different.

  1. Folders can have multiple folders and unlimited
  2. Folders can have files

So, in folder you can create another folder that was the flow.

Now I had to create the breadcrumb so that any user can see the tree structure from where he started diving into the folder. My english is little bit different just try to understand that way I'm trying to explain.

See, the code below how I did that.

 public function show(Folder $folder)
    {
        $id = $folder->id;
        $folderId = $folder->id;
        $breadcrumb = [];
        while ($folderId) {
            $folder = Folder::find($folderId);
            if ($folder) {
                $breadcrumb[] = 
                [
                    'label' => $folder->name,
                    'id' =>  $folder->id,
                ];
                $folderId = $folder->parent_folder_id;
            } else {
                $folderId = null;
            }
        }
    
        $breadcrumb = array_reverse($breadcrumb);
        // echo $folder->id;
        $folders = Folder::query()->where('parent_folder_id', $id)->orderBy('id','desc')->paginate(5);
        return response()->json([
            'status' => 'success',
            'data' =>[
                'folders' => $folders,
                'breadcrumb' => $breadcrumb,
            ],
        ], 200);
    }

Well, I don't know how it should be, this is how I did this. If you have any solution or even any question please don't forget to add your comment below.

Thanks, Gurpreet.

See More: Collections In Laravel