Laravel Eloquent Parent Child In Same Table With Example

  • 10-06-2022
  • 1532
  • Laravel 9
  • Haresh Chauhan

Table management for the project in laravel is the primary question for the developer as especially when you are working with a parent-child relationship like categories and its child categories. So how do you manage that table with two separate tables one for the main category and the second for the sub-category? I suggest you to NO you can also manage this parent-child relationship in single table.

So you can max usage of the table and proper management of parent and child relationship in a single table. There is no need to create two separate tables for it.

In this example, I will tell you how to manage category and sub-category (parent, child) relationship in a single table and how to fetch it as we fetch data while we have to tow separate tables.

Output Preview :

image

You can see in the category listing table name of all the table categories and if the category is a sub-category then in the left side table column its parent category name also will show you.

Migration :

This is my migration file, this is you can see how I manage my category table. if category_id will have null then it will main category. Then category_id stored then it will be sub-category which given category_id'

Also, it should nullable because it's the store's main category. Definitely will have value if the sub-category you are storing.

database/migrations

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoriesTable extends Migration
{
    /**
        * Run the migrations.
        *
        * @return void
        */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->tinyInteger('status')->default(1)->comment('1 active,2 deactive');
            $table->tinyInteger('category_id')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

    /**
        * Reverse the migrations.
        *
        * @return void
        */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

Also, I have given category status that will be inactive if the status will be 2 and active for status 1.

Category Model

In this example, I just made a relationship in the eloquent model using belongsTo method.

Have you noticed? Category model i belongsTo i have relationship in Category same model. So I can fetch that category parent or main category of it.

So when you will fetch the data in a relationship the parent name is also alive.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = [
        'name',
        'status',
        'category_id',
        'description'
    ];

    public function category()
    {
        return $this->belongsTo(Category::class,'category_id','id');
    }
}

CategoryController

Using with i am fetch the parent category relationship and print out it. And then just given simple paginate of ten.

app\Http\Controllers\CategoryController.php

<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
        $categories = Category::with('category')->paginate(10);

        return view('admin.category.category',compact('categories'));
    }
}

I will compact my category to my blade file. This is a category with uses compact function.

Dashboard.blade.php

<div class="box">
    <div class="box-header with-border">
        <div class="row">
        <div class="col-md-4">
            <h3 class="box-title">Category List</h3>
        </div>
        <div class="col-md-8 text-right">
            <a class="btn btn-success float-right" href="{{ route('category.create') }}">Create</a>
        </div>
        </div>
    </div>
    <!-- /.box-header -->
    <div class="box-body">
        <table class="table table-bordered text-center">
        <tr>
            <th style="width: 10px">#</th>
            <th>Name</th>
            <th>Parent Category</th>
            <th>Status</th>
            <th>Created At</th>
            <th>Updated At</th>
        </tr>
        @foreach ($categories as $key => $category)
            <tr>
            <td>{{ $category->id }}</td>
            <td>{{ $category->name }}</td>
            <td>{{ isset($category->category->name) ? $category->category->name : '---' }}</td>
            <td>
                @if($category->status == 1)
                <span class="label label-success">Active</span>
                @else
                <span class="label label-danger">InActive</span>
                @endif
            </td>
            <td>{{ $category->created_at }}</td>
            <td>{{ $category->updated_at }}</td>
            </tr>
            @endforeach
        </table>
    </div>
    <div class="text-right paginate">
    {{ $categories->links('pagination::bootstrap-4') }}
    </div>
</div>

This is my blade file look at how I echo my parent category while we have the parent category of its child.

So this is simple to manage the child-parent relationship in a single table and fetch data also easy and simple to make for the developer project.

Thanks For Reading Our Post.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :