今天,我要来分享下如何在Laravel 5中通过jQuery实现动态类目树结构:有些时候我们确实需要为类目及其子类目生成树结构以便于使用。
在本教程中,我只是简单在Laravel应用中创建一个“categories”表并通过一个嵌套的树结构来管理父类目和子类目。我使用jQuery来生成树视图布局,使用类目模型为层级数据设置关联关系,还为在类目树中创建新类目添加了表单。
在正式开始之前,先贴上最终效果图:
下面正式开始开发之路。
第一步:安装Laravel 5.3应用
如果你还没有安装Laravel 5.3的话,那么第一步肯定是安装它。我们使用Composer进行安装:
composer create-project --prefer-dist laravel/laravel blog
如果没有Homestead之类的开发环境的话,需要在 .env
文件中配置数据库连接信息。
第二步:创建类目表和模型
在这一步中我们使用Laravel提供的Artisan命令为类目表生成迁移文件:
php artisan make:migration create_category_table
运行完该命令之后你会发现在 database/migrations
目录下新生成了一个迁移文件,编辑该文件代码如下:
use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCategoryTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->integer('parent_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop("categories"); } }
然后我们运行如下命令生成该表:
php artisan migrate
创建完数据表之后还需要创建一个与该数据表相对应的模型类 app/Category.php
:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Category extends Model { public $fillable = ['title','parent_id']; /** * Get the index name for the model. * * @return string */ public function childs() { return $this->hasMany('App\Category','parent_id','id') ; } }
第三步:创建路由
在这一步中我们需要创建两个路由,一个用于渲染类目树视图,一个用于添加新的类目。打开 routes/web.php
文件,添加如下两个路由:
Route::get('category-tree-view',['uses'=>'CategoryController@manageCategory']); Route::post('add-category',['as'=>'add.category','uses'=>'CategoryController@addCategory']);
第四步:创建控制器
到了这里,我们需要创建路由中定义的控制器 app/Http/Controllers/CategoryController.php
,编写该文件代码如下:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Category; class CategoryController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function manageCategory() { $categories = Category::where('parent_id', '=', 0)->get(); $allCategories = Category::pluck('title','id')->all(); return view('categoryTreeview',compact('categories','allCategories')); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function addCategory(Request $request) { $this->validate($request, [ 'title' => 'required', ]); $input = $request->all(); $input['parent_id'] = empty($input['parent_id']) ? 0 : $input['parent_id']; Category::create($input); return back()->with('success', 'New Category added successfully.'); } }
第五步:创建视图
在这一步中,我们来创建两个Blade视图文件。首先是 resources/views/categoryTreeview.blade.php
:
<!DOCTYPE html> <html> <head> <title>Laravel Category Treeview Example</title> <link rel="stylesheet" href=http://www.tuicool.com/articles/"https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" /> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js">script > <link href="/css/treeview.css" rel="stylesheet">Manage Category TreeViewCategory List
@foreach($categories as $category)
- {{ $category->title }} @if(count($category->childs)) @include('manageChild',['childs' => $category->childs]) @endif </li> @endforeach </ul> </div> <div class="col-md-6"> <h3>Add New Category</h3> {!! Form::open(['route'=>'add.category']) !!} @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif <div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}"> {!! Form::label('Title:') !!} {!! Form::text('title', old('title'), ['class'=>'form-control', 'placeholder'=>'Enter Title']) !!} <span class="text-danger">{{ $errors->first('title') }}</span> </div> <div class="form-group {{ $errors->has('parent_id') ? 'has-error' : '' }}"> {!! Form::label('Category:') !!} {!! Form::select('parent_id',$allCategories, old('parent_id'), ['class'=>'form-control', 'placeholder'=>'Select Category']) !!} <span class="text-danger">{{ $errors->first('parent_id') }}</span> </div> <div class="form-group"> <button class="btn btn-success">Add New</button> </div> {!! Form::close() !!} </div> </div> </div> </div> </div> <
script src=http://www.tuicool.com/articles/"/js/treeview.js">script >