Laravel5中基於jQuery實現分層級的類目樹結構方法
下面時間財富網小編們來了解一下關於Laravel 5 中基於 jQuery 實現分層級的類目樹結構方法,但願這一篇教程可以給各位帶來幫助,具體的步驟細節以下文介紹。
今天,時間財富網小編要來分享下如何在Laravel 5中經過jQuery實現動態類目樹結構:有些時候時間財富網小編們確實須要爲類目及其子類目生成樹結構以便於使用。
在本教程中,時間財富網小編只是簡單在Laravel應用中建立一個「categories」表並經過一個嵌套的樹結構來管理父類目和子類目。時間財富網小編使用jQuery來生成樹視圖佈局,使用類目模型爲層級數據設置關聯關係,還爲在類目樹中建立新類目添加了表單。
在正式開始以前,先貼上最終效果圖:
laravel-category-tree-view
下面正式開始開發之路。
第一步:安裝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="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">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">Manage Category TreeView</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<h3>Category List</h3>
<ul id="tree1">
@foreach($categories as $category)
<li>
{{ $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="/js/treeview.js"></script>
</body>
</html>
而後是resources/views/manageChild.blade.php:
<ul>
@foreach($childs as $child)
<li>
{{ $child->title }}
@if(count($child->childs))
@include('manageChild',['childs' => $child->childs])
@endif
</li>
@endforeach
</ul>
第六步:添加CSS和JS文件
最後一步,時間財富網小編們來添加視圖文件所須要的CSS和JS文件。
public/css/treeview.css:
.tree, .tree ul {
margin:0;
padding:0;
list-style:none
}
.tree ul {
margin-left:1em;
position:relative
}
.tree ul ul {
margin-left:.5em
}
.tree ul:before {
content:"";
display:block;
width:0;
position:absolute;
top:0;
bottom:0;
left:0;
border-left:1px solid
}
.tree li {
margin:0;
padding:0 1em;
line-height:2em;
color:#369;
font-weight:700;
position:relative
}
.tree ul li:before {
content:"";
display:block;
width:10px;
height:0;
border-top:1px solid;
margin-top:-1px;
position:absolute;
top:1em;
left:0
}
.tree ul li:last-child:before {
background:#fff;
height:auto;
top:1em;
bottom:0
}
.indicator {
margin-right:5px;
}
.tree li a {
text-decoration: none;
color:#369;
}
.tree li button, .tree li button:active, .tree li button:focus {
text-decoration: none;
color:#369;
border:none;
background:transparent;
margin:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
outline: 0;
}
public/js/treeview.js:
$.fn.extend({
treed: function (o) {
var openedClass = 'glyphicon-minus-sign';
var closedClass = 'glyphicon-plus-sign';
if (typeof o != 'undefined'){
if (typeof o.openedClass != 'undefined'){
openedClass = o.openedClass;
}
if (typeof o.closedClass != 'undefined'){
closedClass = o.closedClass;
}
};
/* initialize each of the top levels */
var tree = $(this);
tree.addClass("tree");
tree.find('li').has("ul").each(function () {
var branch = $(this);
branch.prepend("");
branch.addClass('branch');
branch.on('click', function (e) {
if (this == e.target) {
var icon = $(this).children('i:first');
icon.toggleClass(openedClass + " " + closedClass);
$(this).children().children().toggle();
}
})
branch.children().children().toggle();
});
/* fire event from the dynamically added icon */
tree.find('.branch .indicator').each(function(){
$(this).on('click', function () {
$(this).closest('li').click();
});
});
/* fire event to open branch if the li contains an anchor instead of text */
tree.find('.branch>a').each(function () {
$(this).on('click', function (e) {
$(this).closest('li').click();
e.preventDefault();
});
});
/* fire event to open branch if the li contains a button instead of text */
tree.find('.branch>button').each(function () {
$(this).on('click', function (e) {
$(this).closest('li').click();
e.preventDefault();
});
});
}
});
/* 初始化樹狀圖 */
$('#tree1').treed();
好了,至此全部代碼已經編寫完成,你能夠在瀏覽器中查看效果了。
若是你們須要看更多關於PHP編程方面的資訊能夠關注時間財富網php