Today, I'm going to share how the dynamic tree structure is implemented through jquery in Laravel 5: There are times when we really need to create trees for the class and its subclasses for ease of use.
In this tutorial, I simply create a "categories" table in the Laravel application and manage the parent class and subclasses through a nested tree structure. I use jquery to generate a tree view layout, use the class mesh model to set the association relationship for the hierarchical data, and add a form to create a new class in the class tree.
Before the formal start, put the final effect chart:
Laravel-category-tree-view
The following is the official beginning of the development of the road.
First step: Install Laravel 5.3 Application
If you haven't installed Laravel 5.3, then the first step is definitely to install it. We use composer for installation:
Composer Create-project--prefer-dist Laravel/laravel Blog
If you don't have a development environment like homestead, you need to configure database connection information in the. env file.
Step Two: Create the class table and model
In this step we use the Artisan command provided by Laravel to generate migrated files for the class table:
PHP Artisan make:migration create_category_table
After you run the command, you will find that the new Database/migrations directory is a migration file, editing the file code as follows:
Use Illuminate\support\facades\schema;
Use Illuminate\database\schema\blueprint;
Use illuminate\database\migrations\migration;
Class Createcategorytable extends migration
{
/**
* Run/mi Grations.
*
* @return void
*/
& nbsp; 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::d ROP ("categories");
}
}
We then run the following command to generate the table:
PHP Artisan Migrate
After you create the datasheet, you also need to create a model class app/category.php that corresponds to the data table:
<?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 ');
}
}
Step three: Create a route
In this step we need to create two routes, one for rendering the class tree view, and one for adding a new class. Open the routes/web.php file and add the following two routes:
Route::get (' Category-tree-view ', [' Uses ' => ' categorycontroller@managecategory ']);
Route::p ost (' Add-category ', [' as ' => ' add.category ', ' uses ' => ' categorycontroller@addcategory ']);
Step Fourth: Create a controller
Here, we need to create the controller app/http/controllers/categorycontroller.php defined in the route, and write the file code as follows:
<?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::p Luck (' 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. ');
}
}
Step Fifth: Create a View
In this step, we will create two blade view files. The first is resources/views/categorytreeview.blade.php:
<! DOCTYPE html>
<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" >
<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" >
<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" >
{!! 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" >x</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>
And then the 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>
Sixth step: Add CSS and JS files
In the final step, we'll add the CSS and JS files needed for the view file.
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: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 */
& nbsp; tree.find ('. Branch. Indicator '). each (function () {
$ (this). On (' click ', Function () {
$ (this). Closest (' Li '). Click ();
});
});
/* Fire event to open branch if the contains-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 ();
});
});
}
});
/* Initialize tree Map/*
$ (' #tree1 '). treed ();
OK, so all the code has been written so that you can see the effect in the browser.