Laravel Same Table Parent Child Relationship Example

https://www.codecheef.org/user/img/fevicon.png

Laravel Same Table Parent Child Relationship Example

Posted By

Mahedi Hasan

Category

Framework

Sub-category

Laravel 8.x

March 25, 2021

Hello Laravel developers in this example tutorial i will explain laravel multilevel nested data example. That mean just assume that we have a department and we have a section. Every section has a team member and many member works under the team member. So now we have to design that model and we need to define that relationship in Laravel.

I will use laravel eloquent parent child same table to show this laravel parent child relationship. In this example we will see that multilevel nested category example in Laravel. So simply see the below situation.

- Department
  - Section 1
    - Team 1
    - Team 2
  - Section 2
...

 

Now simply think we have a Test model and we will design our relationship via this model.

App\Models\Test.php


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    use HasFactory;

    protected $parentColumn = 'parent_id';

    public function parent()
    {
        return $this->belongsTo(Test::class,$this->parentColumn);
    }

    public function children()
    {
        return $this->hasMany(Test::class, $this->parentColumn);
    }

    public function allChildren()
    {
        return $this->children()->with('allChildren');
    }

}

 

As you can see, it is a very simple piece of code but powerful enough to get the job done. Now we can access like that

$department = Test::find(3);
$parent = $department->parent;

$department = Test::find(3);
$children = $department->children;

$department = Test::find(3);
$children = $department->allChildren;

 

I hope that this is as useful for you as it was for our team! Feel free to use it! 🚀

 

Laravel News Links