摘要:我們知道,做后臺管理系統需要很多表格用來展示我們的數據,筆者在項目中使用過,對于快速開發來說,將是一個不錯的選擇。
我們知道,做后臺管理系統需要很多表格用來展示我們的數據,筆者在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 !
下載:項目源碼
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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框架學習之路。如需...
閱讀 1634·2023-04-26 02:11
閱讀 2979·2023-04-25 16:18
閱讀 3711·2021-09-06 15:00
閱讀 2630·2019-08-30 15:55
閱讀 1934·2019-08-30 13:20
閱讀 2051·2019-08-26 18:36
閱讀 3121·2019-08-26 11:40
閱讀 2538·2019-08-26 10:11