How to create a multilevel category and subcategory in Laravel
You need to meet categories and subcategories in most projects you work on in Laravel or any language. As far as categories are concerned, the tree structure is the best listing method we can use in our web applications.
Today I'm going to show you how to create nested category tree view structure in Laravel. You can simple following the below steps to get category tree view in your website.
You need to meet categories and subcategories in most projects you work on in Laravel or any language. As far as categories are concerned, the tree structure is the best listing method we can use in our web applications.
Today I'm going to show you how to create nested category tree view structure in Laravel. You can simple following the below steps to get category tree view in your website.
Step 1: Open project folder in command line and enter command `php artisan make:model Category -mcr`. This will create model, migration and controller file.
Step 2: Open migration file `laravel-app/database/migrations/2023_01_11_122023_create_category_table.php` and add columns in it.
<?php
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->string('slug')->nullable();
$table->integer('parent_id')->nullable();
$table->text('thumbnail')->nullable();
$table->timestamps();
});
}
?>
Step 3: Open Catagory.php model file `laravel-app/app/Models/Category.php` and add children function in it.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function children(){
return $this->hasMany(Category::Class,'parent_id')->with('children');
}
}
?>
Step 4: Open file `laravel-app/app/Http/Controllers/CategoryController.php` and paste below 2 functions in it.
<?php
public function multiLevelCategory(){
$categories = Category::with('children')->get();
$this->generateCategories($categories);
}
public function generateCategories($categories){
foreach ($categories as $category) {
echo '';
echo '- ' . $category->category . '
';
if (count($category->children) > 0) {
$this->generateCategories($category->children);
}
echo '
';
}
}
?>
Step 5: Open web.php file and add below get route in it.
Route::get('/list', 'CategoryController@multiLevelCategory');
Open link http://127.0.0.1:8000/list.
Recommanded Articles
- How to create a multilevel category and subcategory in Laravel
- How to check YouTube video exist Laravel validation
- Multiple user roles authentication Laravel 8
- Deploy Laravel project from local to production server
- Make custom pagination URL in Laravel without query strings
- Web Scraping in Laravel using Goutte
- Insert values during migration run laravel
- Validation for string characters only with custom message in Laravel
- Add new columns in a table Laravel
- How to create foreign key constraints in Laravel
Latest Comments
Tanja
03 Jan 2024