Create Multiple Subcategories in Laravel 5.8

Các bạn cũng thường nhìn thấy rằng trong các website bán hàng hiện này điều có nhiều Categories và SubCategories, chính vì thế mà hôm này mình chia sẻ với mọi người cách tạo một Categories trong Eloquent Laravel 5.8. Thường các bạn dùng Đệ quy trong PHP để sử dụng Categories có nhiều danh mục. Nhưng trong Laravel thì sao, các bạn cùng mình tìm hiểu nhé!

create multiple subcategories in laravel 5.8

Đầu tiền chúng ta cần tạo table categories như sau:

php artisan make:migration create_categories_table --create=categories

Sau khi tạo xong bạn vào thư mục database/migrations tìm file vừa tạo và sửa lại như sau:

Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->unsignedBigInteger('category_id')->nullable();
    $table->foreign('category_id')->references('id')->on('categories');
    $table->timestamps();
    
});

Trong đoạn code bên trên chúng ta cũng đã biết, thường các danh mục cha có category_id = 0 hoặc bằng NULL, để ta có thể nhận biết được thư mục cấp Cha và Con
Tiếp theo chúng ta tạo Eloquent Model Relationship cho Categories:

php artisan make:model Category

Đầu tiên ta vào thư mục App\Categories.php thêm phương thức hasMany categories() và phương thức để lấy các subcategories con

class Category extends Model
{

    public function categories()
    {
        return $this->hasMany(Category::class);
    }
    public function childrenCategories()
    {
        return $this->hasMany(Category::class)->with('categories');
    }

}

Nếu chúng ta gọi Category::with('categories') sẻ return về cho chúng ta một danh mục con mà nó nhận thấy được trong liên kết, Còn khi chúng ta gọi Category::with('childrenCategories') nó sẽ cung cấp cho ta nhiều cấp trong Categories được tìm thấy.

File CategoryController.php như sau:

public function index()
{
    $categories = Category::whereNull('category_id')
    ->with('childrenCategories')
    ->get(); 
   // dd($categories);
   return view('categories', compact('categories'));
    
}

Tạo categories.blale.php để hiện thị như sau:

<ul>
    @foreach ($categories as $category)
        <li>{{ $category->name }}</li>
        <ul>
        @foreach ($category->childrenCategories as $childCategory)
            @include('child_category', ['child_category' => $childCategory])
        @endforeach
        </ul>
    @endforeach
</ul>

File child_category.blade.php

<li>{{ $child_category->name }}</li>
@if ($child_category->categories)
    <ul>
        @foreach ($child_category->categories as $childCategory)
            @include('child_category', ['child_category' => $childCategory])
        @endforeach
    </ul>
@endif

Ở bên trên chúng ta show các Category ra nhưng bạn nhìn thấy ta có include thêm một child_category.blale.php, tại sao chúng ta làm điều này, nếu chúng ta làm như vậy sẽ cho chúng ta show ra được nhiều cấp hơn và không cần xác định số dòng foreach mặc định của cấp độ danh mục
Tiếp theo chúng ta tạo Route cho hiển thị Categories

Route::get('categories', 'CategoryController@index');

Vậy là xong giờ chúng ta chỉ cần chạy đường dẫn để test thử xem thôi! http://localhost/project/public/categories

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)