摘要:我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在项目中使用过,对于快速开发来说,将是一个不错的选择。
我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在tp项目中使用过datatables,对于快速开发来说,datatables将是一个不错的选择。
首先来看一下最终的效果:
准备工作:
1、首先,确保你的laravel配置正确(站点能够正常访问、数据库连接正常...)
2、下载Datatables资源文件(AdminLTE中包含了Datatables资源文件,读者使用其他模板需另行引入的请自行百度),并在页面中引入,确保资源文件能够正确加载。
3、文档:Laravel Datatables开发文档
系统要求:
Laravel 5.5+
jQuery DataTables v1.10.x
ok,开始动手!(以administrator页面为例)
1、安装composer包
composer require yajra/laravel-datatables-oracle:^8.0
如果你需要使用datatables的全部插件可使用以下命令安装
composer require yajra/laravel-datatables:^1.0
2、配置Datatables(此步骤可省,但还是配置下,确保后续不会出错)
安装完成之后,打开config/app.php,键入如下代码
"providers" => [ // ... YajraDataTablesDataTablesServiceProvider::class, ],
使用命令发布配置和资源文件
php artisan vendor:publish --tag=datatables
3、创建administrator模型
php artisan make:model Models/Administrator -m
编辑数据库迁移文件
engine = "InnoDB"; $table->increments("id"); $table->string("login_name")->unique(); $table->string("display_name"); $table->string("password"); $table->string("avatar")->nullable(); $table->rememberToken(); $table->tinyInteger("status")->default(1); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists("administrators"); } }
4、创建AdministratorDatatable
php artisan datatables:make Administrator
此命令会生成DataTables/AdministratorDatatable.php,打开并编辑:
setRowClass("text-center") ->editColumn("avatar", function (Administrator $administrator) { return "avatar."">"; }) ->editColumn("roles", function (Administrator $administrator) { return $administrator->roles->map(function ($role) { return "".$role->identifier."[".$role->name."]".""; })->implode(""); }) ->editColumn("status", function (Administrator $administrator) { if ($administrator->status == 1) { return "正常"; } return "禁用"; }) ->rawColumns(["avatar", "status", "roles", "action"]) ->addColumn("action", function (Administrator $administrator) { $edit_path = admin_base_path("auth/administrators/".$administrator->id."/edit"); $delete_path = admin_base_path("auth/administrators/".$administrator->id); return "". " 编辑". "". " 删除"; }); } /** * Get query source of dataTable. * * @param AppModelsAdministrator $model * @return IlluminateDatabaseEloquentBuilder */ public function query(Administrator $model) { return $model->newQuery()->select("id", "login_name", "display_name", "avatar", "status", "created_at", "updated_at"); } /** * Optional method if you want to use html builder. * * @return YajraDataTablesHtmlBuilder */ public function html() { return $this->builder() ->addTableClass("table-bordered table-striped") ->columns($this->getColumns()) ->minifiedAjax("administrators") ->addAction(["title" => "操作", "class" => "text-center"]) ->parameters([ "dom" => "Bfrtip", "buttons" => [ ["extend" => "create", "text" => " 创建"], ["extend" => "excel", "text" => " 导出"], ["extend" => "print", "text" => " 打印"], ["extend" => "reload", "text" => " 刷新"], ], ]); } /** * 获取数据列 * * @return array */ protected function getColumns() { return [ ["name" => "id", "data" => "id", "title" => "ID", "class" => "text-center"], ["name" => "login_name", "data" => "login_name", "title" => "登录名", "class" => "text-center", "orderable" => false], ["name" => "display_name", "data" => "display_name", "title" => "显示名", "class" => "text-center", "orderable" => false], ["name" => "avatar", "data" => "avatar", "title" => "头像", "class" => "text-center", "orderable" => false], ["name" => "status", "data" => "status", "title" => "状态", "class" => "text-center"], ["name" => "roles", "data" => "roles", "title" => "角色", "class" => "text-center", "orderable" => false], ["name" => "created_at", "data" => "created_at", "title" => "创建时间", "class" => "text-center"], ["name" => "updated_at", "data" => "updated_at", "title" => "更新时间", "class" => "text-center"], ]; } /** * 设置导出文件名 * * @return string */ protected function filename() { return "Administrator_" . date("YmdHis"); } /** * 打印列 * @var array */ protected $printColumns = ["id", "login_name", "display_name", "created_at", "updated_at"]; }
5、创建视图文件resource/views/admin/auth/administrator/index.blade.php(视图文件使用布局,读者可参考之前的文章或参考源码)
@extends("admin::layouts.layout") @section("content")管理员 列表
{!! $dataTable->scripts() !!} @endsection
创建视图文件resource/views/admin/auth/administrator/create.blade.php
@extends("admin::layouts.layout") @section("content")管理员 创建
@endsection
创建视图文件resource/views/admin/auth/administrator/edit.blade.php
@extends("admin::layouts.layout") @section("content")管理员 编辑
@endsection
6、创建administrator控制器
php artisan make:controller Admin/Auth/AdministratorController --resource
打开Admin/Auth/AdministratorController.php并编辑
render(admin_view_path("auth.administrator.index")); } /** * Show the form for creating a new resource. * * @return IlluminateHttpResponse */ public function create() { $roles = Role::all(); return view(admin_view_path("auth.administrator.create"))->with([ "roleList" => $roles, ]); } /** * * @param Request $request * @return IlluminateHttpRedirectResponse|IlluminateRoutingRedirector * @throws Exception */ public function store(Request $request) { $this->validate($request, [ "login_name" => "required|unique:administrators", "display_name" => "required", "roles" => "required", "password" => "required|min:6|confirmed", "password_confirmation" => "required|min:6", ],[ "login_name.required" => "请输入登录名", "login_name.unique" => "该登录名已存在", "display_name.required" => "请输入显示名", "roles.required" => "请选择一个或多个角色", "password.required" => "请输入密码", "password.min" => "密码至少6位", "password.confirmed" => "两次输入密码不一致", "password_confirmation.required" => "请输入确认密码", "password_confirmation.min" => "密码至少6位", ]); $administrator = new Administrator(); $administrator->login_name = $request->get("login_name"); $administrator->display_name = $request->get("display_name"); $administrator->password = Hash::make($request->get("password")); $roles = $request->get("roles"); DB::beginTransaction(); try { if (!$administrator->save()) { throw new Exception("保存失败"); } if (!$administrator->updateRelation($roles)) { throw new Exception("保存失败"); } DB::commit(); admin_toastr("角色更新成功!"); return redirect(admin_base_path("auth/administrator")); } catch (Exception $e) { $error = $e->getMessage(); DB::rollBack(); admin_toastr($error, "error"); return redirect()->back()->withInput()->withErrors([ "error" => $error ]); } } /** * Display the specified resource. * * @param int $id * @return IlluminateHttpResponse */ public function show($id) { } /** * Show the form for editing the specified resource. * * @param int $id * @return IlluminateHttpResponse */ public function edit($id) { $administrator = Administrator::find($id); $roles = Role::all(); return view(admin_base_path("auth.administrator.edit"))->with([ "roleList" => $roles, "administrator" => $administrator ]); } /** * @param Request $request * @param $id * @return IlluminateHttpRedirectResponse|IlluminateRoutingRedirector * @throws Exception */ public function update(Request $request, $id) { $this->validate($request, [ "login_name" => "required|unique:administrators", "display_name" => "required", "roles" => "required", ],[ "login_name.required" => "请输入登录名", "login_name.unique" => "该登录名已存在", "display_name.required" => "请输入显示名", "roles.required" => "请选择一个或多个角色", ]); $administrator = Administrator::find($id); $administrator->login_name = $request->get("login_name"); $administrator->display_name = $request->get("display_name"); $roles = $request->get("roles"); DB::beginTransaction(); try { if (!$administrator->save()) { throw new Exception("保存失败"); } if (!$administrator->updateRelation($roles)) { throw new Exception("保存失败"); } DB::commit(); admin_toastr("角色更新成功!"); return redirect(admin_base_path("auth/administrator")); } catch (Exception $e) { $error = $e->getMessage(); DB::rollBack(); admin_toastr($error, "error"); return redirect()->back()->withInput()->withErrors([ "error" => $error ]); } } /** * Remove the specified resource from storage. * * @param int $id * @return IlluminateHttpResponse */ public function destroy($id) { if (Administrator::find($id)->delete()) { return response()->json([ "status" => true, "message" => "删除成功!", ]); } else { return response()->json([ "status" => false, "message" => "删除失败,请重试!", ]); } } }
别忘了配置路由:
config("admin.route.prefix"), "namespace" => config("admin.route.namespace"), "middleware" => config("admin.route.middleware"), ], function (Router $router) { //后台控制面板 $router->get("/", "HomeHomeController@index")->name("home.index"); //登录页面 $router->get("login", "AuthLoginController@getLogin")->name("login.getLogin"); //登录 $router->post("login", "AuthLoginController@postLogin")->name("login.postLogin"); //注销登录 $router->post("logout", "AuthLoginController@postLogout")->name("login.logout"); /** * auth模块 */ //后台用户管理 $router->resource("auth/administrators", "AuthAdministratorController"); //权限管理 $router->resource("auth/permissions", "AuthPermissionController"); //权限策略管理 $router->resource("auth/policies", "AuthPolicyController"); //角色管理 $router->resource("auth/roles", "AuthRoleController"); //菜单管理 $router->resource("auth/menus", "AuthMenuController"); /** * blog模块 */ //文章管理 $router->resource("blog/articles", "BlogArticleController"); });
7、本地化:创建一个多带带文件,如datatable-language.js并在页面中引入
$.fn.dataTable.defaults.oLanguage = { "sProcessing": "处理中...", "sLengthMenu": "显示 _MENU_ 项结果", "sZeroRecords": "没有匹配结果", "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项", "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项", "sInfoFiltered": "(由 _MAX_ 项结果过滤)", "sInfoPostFix": "", "sSearch": "搜索:", "sUrl": "", "sEmptyTable": "表中数据为空", "sLoadingRecords": "载入中...", "sInfoThousands": ",", "oPaginate": { "sFirst": "首页", "sPrevious": "上页", "sNext": "下页", "sLast": "末页" }, "oAria": { "sSortAscending": ": 以升序排列此列", "sSortDescending": ": 以降序排列此列" } }; $.fn.dataTable.defaults.autoWidth = false;
写在最后:表格中一些按钮事件请读者根据需要自行编码,这里只给出一个例子:删除按钮事件(引入了sweetalert插件以及toastr插件,如有需要请参考源码)
//datatables删除按钮 $("#pjax-container").on("click", ".row-delete", function () { var del_url = $(this).data("url"); swal({ title: "确定删除此项?", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "确 定", closeOnConfirm: false, cancelButtonText: "取 消" }, function(){ $.ajax({ method: "post", url: del_url, data: { _method:"delete", _token:csrf_token, }, success: function (data) { if (typeof data === "object") { if (data.status) { swal(data.message, "", "success"); $.pjax.reload("#pjax-container"); } else { swal(data.message, "", "error"); } } } }); }); });
ok,大功告成,enjoy it !
下载:项目源码
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/28701.html
摘要:我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在项目中使用过,对于快速开发来说,将是一个不错的选择。 我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在tp项目中使用过datatables,对于快速开发来说,datatables将是一个不错的选择。首先来看一下最终的效果:showImg(https://segmentfault.com/img/bVbbpf0?...
摘要:我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在项目中使用过,对于快速开发来说,将是一个不错的选择。 我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在tp项目中使用过datatables,对于快速开发来说,datatables将是一个不错的选择。首先来看一下最终的效果:showImg(https://segmentfault.com/img/bVbbpf0?...
摘要:我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在项目中使用过,对于快速开发来说,将是一个不错的选择。 我们知道,做后台管理系统需要很多表格用来展示我们的数据,笔者在tp项目中使用过datatables,对于快速开发来说,datatables将是一个不错的选择。首先来看一下最终的效果:showImg(https://segmentfault.com/img/bVbbpf0?...
摘要:继第一篇文章发布之后框架学习之路一前后台用户认证分离,忙着项目上的事情,一直没有时间写文章。进入到新公司后,忙里偷闲,继续我的框架学习之路。附件笔者的布局全局文件整页刷新时,菜单显示删除按钮确定删除此项确定取消 继第一篇文章发布之后laravel框架学习之路(一)前后台用户认证分离,忙着项目上的事情,一直没有时间写文章。进入到新公司后,忙里偷闲,继续我的laravel框架学习之路。如需...
摘要:继第一篇文章发布之后框架学习之路一前后台用户认证分离,忙着项目上的事情,一直没有时间写文章。进入到新公司后,忙里偷闲,继续我的框架学习之路。附件笔者的布局全局文件整页刷新时,菜单显示删除按钮确定删除此项确定取消 继第一篇文章发布之后laravel框架学习之路(一)前后台用户认证分离,忙着项目上的事情,一直没有时间写文章。进入到新公司后,忙里偷闲,继续我的laravel框架学习之路。如需...
阅读 1620·2023-04-26 02:11
阅读 2921·2023-04-25 16:18
阅读 3657·2021-09-06 15:00
阅读 2578·2019-08-30 15:55
阅读 1818·2019-08-30 13:20
阅读 1985·2019-08-26 18:36
阅读 3055·2019-08-26 11:40
阅读 2501·2019-08-26 10:11