前言说明
前言说明
无限级分类功能广泛应用于各类网站开发中,属于开发者必须掌握的核心技能。尽管网络上存在大量相关文档,但部分资料内容不够详尽、存在错误或无法达到预期效果。实际上,该功能的实现逻辑并不复杂,本文将详细演示具体的实现过程。

创建模型控制器与迁移文件
创建模型、控制器与数据迁移文件
此处直接利用 Artisan 命令行工具进行快速构建。
# -a 其实就是all,创建包含模型,控制器(资源),数据迁移文件(工厂模型、seed)
php artisan make:model -a Category
执行上述命令后,系统将自动完成资源控制器的创建工作。

调整数据迁移脚本
调整数据迁移脚本
首先定位并编辑名为 xxx_create_categories_table 的数据迁移文件。
打开该文件后,修改其中的 up 方法,在其中添加所需的数据库字段定义。
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('title', 100)->comment('分类名称');
$table->string('name', 100)->comment('分类标识');
$table->string('description', 255)->nullable()->comment('分类描述');
$table->integer('pid')->default(0)->comment('分类id');
$table->integer('level')->default(1)->comment('分类层级');
$table->integer('sort')->default(0)->comment('排序');
$table->integer('status')->default(1)->comment('状态:0-禁用,1-正常');
$table->timestamps();
});

执行迁移操作
执行迁移操作
php artisan migrate
嵌套模型读取数据
采用嵌套模型方式读取数据
//App\Models\Category.php
public function categories()
{
return $this->hasMany(self::class, 'pid', 'id')->with('categories');
}
在控制器中进行调用处理
//app\Http\controllers\CategooryController.php
# use模型
use App\Models\Category;
public function index()
{
$categories = Category::with('categories')->where('pid', 0)->get();
return view('category.index', compact('categories'));
}
配置路由规则
配置路由规则
前往 routes/web.php 文件,插入如下代码片段:
Route::get('category', 'CategoryController@index');
使用 Blade 模板渲染
使用 Blade 模板进行页面渲染
此处采用递归调用的方式进行视图渲染。
在 resources/views/categories.blade.php 文件中编写如下内容:
编号
分类名称
分类标识
分类描述
创建时间
状态
操作
@foreach ($categories as $category)
{{ $category->id }}
{{ $category->title }}
{{ $category->name }}
{{ $category->description }}
{{ $category->created_at }}
{{ $category->status }}
@foreach ($category->categories as $childCategory)
@include('category.child_category', ['child_category' => $childCategory])
@endforeach
@endforeach
递归部分需加载自身的子模板 child_category.blade.php
{{ $child_category->id }}
|{{ str_repeat('--',$child_category->level-1) }} {{ $child_category->title }}
{{ $child_category->name }}
{{ $child_category->description }}
{{ $child_category->created_at }}
{{ $child_category->status }}
@if ($child_category->categories)
@foreach ($child_category->categories as $childCategory)
@include('category.child_category', ['child_category' => $childCategory])
@endforeach
@endif
最终效果展示
最终效果展示

总结回顾
总结回顾
至此,关于 Laravel 7 无限级分类最新实现方法的介绍已告一段落。如需了解更多相关内容,建议搜索本站历史文章或继续浏览后续推荐内容,感谢大家的支持!