Jquery таблица данных в laravel Vuejs с добавлением, обновлением, удалением и разбиением на страницы на стороне сервера и т. Д. - PullRequest
0 голосов
/ 28 марта 2020

Через несколько недель я обнаружил, как реализовать таблицу данных Jquery в laravel Vuejs с функциями добавления, обновления, удаления и разбиения на страницы на стороне сервера, сортировки, фильтрации и поиска. Это только для целей. Я делюсь этой информацией, возможно, многие разработчики будут ее искать, и я надеюсь, что никто не даст мне (минус баллы)

Маршрут

Route::post('getAllExpense', 'API\ExpensesController@getAll');
Route::apiResources(['Expense' => 'API\ExpensesController']);
Route::post('getAllExpense', 'API\ExpensesController@getAll');
Route::delete('multipledeleteExpense', 'API\ExpensesController@multipledelete');
Route::get('getExpenseByid', 'API\ExpensesController@getExpenseByid');

Расходы. vue

<template>
  <div class="container">
    <div class="vld-parent">
      <loading
        :active.sync="isLoading"
        :can-cancel="true"
        :on-cancel="onCancel"
        :is-full-page="fullPage"
        color="#3cb371"
      ></loading>
    </div>
    <div class="col-md-12 col-sm-12 col-xs-12">
      <div class="x_panel">
        <div class="x_title">
          <h2>د لګښتونه لست</h2>
          <ul class="nav navbar-right panel_toolbox">
            <li>
              <a class="collapse-link">
                <i class="fa fa-chevron-up"></i>
              </a>
            </li>

            <li>
              <a class="close-link">
                <i class="fa fa-close"></i>
              </a>
            </li>
          </ul>
          <div class="clearfix"></div>
        </div>
        <div class="x_content">
          <div
            id="datatable-buttons_wrapper"
            class="dataTables_wrapper form-inline dt-bootstrap no-footer"
          >
            <div class="dt-buttons btn-group" style="margin-bottom:5px;">
              <button
                class="btn btn-success buttons-copy buttons-html5 btn-sm"
                tabindex="0"
                aria-controls="datatable-buttons"
                @click="newModal"
              >نوی لګښتونه خوندی کړی</button>
              <button
                class="btn btn-danger buttons-copy buttons-html5 btn-sm"
                tabindex="0"
                aria-controls="datatable-buttons"
                @click="delt"
              >د ګڼ ړنګول</button>
              <a
                href="Report/viewer.php"
                target="_blank"
                class="btn btn-info buttons-copy buttons-html5 btn-sm"
                tabindex="0"
                aria-controls="datatable-buttons"
              >
                <i class="fa fa-file-text"></i>
                راپورونه
              </a>
            </div>
            <div class="row">
              <div class="col-sm-12">
                <table id="datatable1" class="table table-striped">
                  <thead>
                    <tr>
                      <!-- <th style="width:1%;">
                        <input type="checkbox" @click="selectAll" v-model="allSelected" />
                      </th>-->
                      <th>کوډ</th>
                      <th>ډول</th>
                      <th>نیټه</th>
                      <th>پیسی</th>
                      <th>شرح</th>
                      <th>تنظیمات</th>
                    </tr>
                  </thead>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- insert modal -->
    <div
      class="modal fade"
      id="edit"
      tabindex="-1"
      role="dialog"
      aria-labelledby="addNewLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content"></div>
      </div>
    </div>
    <div
      class="modal fade"
      id="addNew"
      tabindex="-1"
      role="dialog"
      aria-labelledby="addNewLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" v-show="!editMode" id="addNewLabel">خوندی کړی</h5>
            <h5 class="modal-title" v-show="editMode" id="addNewLabel">دلګښت سمول</h5>

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true" style="margin-right: 317px;">&times;</span>
            </button>
          </div>
          <form @submit.prevent="editMode ? updateExpense() : createExpense()">
            <div class="modal-body">
              <div class="form-group">
                <select
                  name="expens_type_id"
                  id="expens_type_id"
                  :class="{ 'is-invalid': form.errors.has('expens_type_id') }"
                  class="form-control"
                  v-model="form.expens_type_id"
                >
                  <option value selected>دلګښت ډول ټاکنه</option>
                  <option
                    v-for="ExpenseType in ExpensesType"
                    :key="ExpenseType.id"
                    :value="ExpenseType.id"
                  >
                    {{
                    ExpenseType.name
                    }}
                  </option>
                </select>
                <has-error :form="form" field="expens_type_id"></has-error>
              </div>

              <div class="form-group">
                <input
                  dir="rtl"
                  id="text1"
                  v-model="form.date"
                  placeholder="نیټه "
                  type="date"
                  name="date"
                  class="form-control"
                  :class="{ 'is-invalid': form.errors.has('date') }"
                />
                <has-error :form="form" field="date"></has-error>
              </div>
              <div class="form-group">
                <input
                  dir="rtl"
                  id="text1"
                  v-model="form.amount"
                  placeholder="پیسی "
                  type="number"
                  name="amount"
                  class="form-control"
                  :class="{ 'is-invalid': form.errors.has('amount') }"
                />
                <has-error :form="form" field="amount"></has-error>
              </div>
              <div class="form-group">
                <textarea
                  v-model="form.description"
                  placeholder="تشریح"
                  type="text"
                  name="description"
                  class="form-control"
                  :class="{ 'is-invalid': form.errors.has('description') }"
                ></textarea>

                <has-error :form="form" field="description"></has-error>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">لغوه کړی</button>

                <button
                  v-show="editMode"
                  :disabled="form.busy"
                  type="submit"
                  class="btn btn-success"
                >تازه کړی</button>
                <button
                  v-show="!editMode"
                  :disabled="form.busy"
                  type="submit"
                  class="btn btn-primary"
                >خوندی کړی</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
    <!-- end of Insert modal -->
  </div>
</template>

<script>
import Datepicker from "vuejs-datepicker";
import Loading from "vue-loading-overlay";
import { DataTable } from "datatables";
// // // Import stylesheet
import "vue-loading-overlay/dist/vue-loading.css";
export default {
  components: {
    Datepicker,

    Loading
  },

  data() {
    return {
      isLoading: false,
      fullPage: true,
      hidebutton: true,
      color: "blue",
      tblData: null,
      editMode: false,
      ExpensesType: [],
      Expenses: {},
      Expense: [],
      Expenses2: [],
      selected: [],
      allSelected: false,
      checkedRows: [],
      data: [],
      url: "api/getAllExpense",
      form: new Form({
        id: "",
        expens_type_id: "",
        amount: "",
        date: "",
        description: ""
      })
    };
  },
  computed: {},
  methods: {
    selectAll: function() {
      this.checkedRows = [];

      if (!this.allSelected) {
        for (user in this.data) {
          this.checkedRows.push(this.data[user].id);
        }
      }
    },
    doAjax() {
      this.isLoading = true;
      this.color = "blue";
      // simulate AJAX
      setTimeout(() => {
        this.isLoading = false;
      }, 1000);
    },
    onCancel() {
      console.log("User cancelled the loader.");
    },
    refrash: function() {
      $("#addNew").modal("hide");
    },
    loadallExpenses() {
      axios.get("api/Expense").then(({ data }) => (this.Expenses = data));
    },
    getResults(page = 1) {
      this.isLoading = true;
      this.color = "blue";
      // simulate AJAX
      setTimeout(() => {
        this.isLoading = false;
      }, 500);
      axios
        .get("api/Expense?page=" + page)
        .then(response => {
          this.Expenses = response.data;
        })

        .then(
          function(response) {
            this.Expenses = response.data.data;
          }.bind(this)
        );
    },
    updateExpense() {
      if (this.form.expens_type_id == "") {
        toast.fire({
          icon: "warning",
          html: "<h5>د لکښت ډول اړین دی.</h5>"
        });
      } else if (this.form.amount == "") {
        toast.fire({
          icon: "warning",
          html: "<h5>پیسی  اړین دی.</h5>"
        });
      } else if (this.form.date == "") {
        toast.fire({
          icon: "warning",
          html: "<h5>نیټه  اړین ده.</h5>"
        });
      } else {
        this.form
          .put("api/Expense/" + this.form.id)
          .then(() => {
            $("#addNew").modal("hide");
            toast.fire({
              icon: "success",
              html: "<h5 >معلومات په بریالیتوب سره خوندي شول.</h5> "
            });
            Fire.$emit("refreshPage");
          })
          .catch(e => {
            console.log(e);
          });
      }
    },
    detailModal(emp1) {
      this.form.reset();
      $("#addNew3").modal("show");
      this.form.fill(emp1);
    },
    editModal(id) {
      axios
        .get("api/getExpenseByid?id=" + id)
        .then(({ data }) => (this.Expense = data))
        .then(d => {
          //console.log("data console", this.Expense[0].id);
          this.editMode = true;
          this.form.reset();
          $("#addNew").modal("show");
          this.form.fill(this.Expense[0]);
        });
    },

    newModal() {
      this.editMode = false;
      this.form.reset();
      if (this.ExpensesType != undefined && this.ExpensesType.length == 0) {
        toast.fire({
          icon: "warning",
          html: "<h5>لږ ترلږه یو دلکښت ډول خوندی کړی.</h5>"
        });
      } else {
        $("#addNew").modal("show");
      }
    },
    delt() {
      var chekboxs = document.getElementById("chekboxs");
      if (chekboxs.checked || this.allSelected) {
        swal
          .fire({
            title: "آیا تاسې ډاډه یاست چې دا معلومات له منځه يوسئ؟",
            text: "تاسو دا معلومات بیا راګرځولی نشی!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "هو ، دا معلومات ړنګ کړئ!",
            cancelButtonText: "لغوه کړی"
          })
          .then(result => {
            //Send request to the server
            if (result.value) {
              axios
                .delete("api/multipledeleteExpense", {
                  params: { id: this.checkedRows }
                })
                .then(() => {
                  toast.fire({
                    icon: "success",
                    html: "<h5>معلومات په بریالیتوب سره ړنګ شول</h5>"
                  });
                  Fire.$emit("refreshPage");
                })
                .catch(e => {
                  console.log(e);
                });
            }
          });
      } else {
        toast.fire({
          icon: "warning",
          html:
            "<h5>د ړنګولو لپاره تاسو  کوم معلومات نه دی ټاکلی ،مهرباني وکړئ  معلومات  وټاکئ!</h5>"
        });
      }
    },

    deleteExpense(id) {
      swal
        .fire({
          title: "آیا تاسې ډاډه یاست چې دا معلومات له منځه يوسئ؟",
          text: "تاسو دا معلومات بیا راګرځولی نشی!",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "هو ، دا معلومات ړنګ کړئ!",
          // buttons: ["Select Patient?", "Speed Case?"],
          cancelButtonText: "لغوه کړی"
        })
        .then(result => {
          //Send request to the server
          if (result.value) {
            this.form
              .delete("api/Expense/" + id)
              .then(() => {
                toast.fire({
                  type: "success",
                  html: "<h5>معلومات په بریالیتوب سره ړنګ شول</h5>"
                });
                Fire.$emit("refreshPage");
              })
              .catch(e => {
                console.log(e);
              });
          }
        });
    },
    loadExpenses() {
      this.$Progress.start();
      axios.get("api/Expense").then(({ data }) => (this.Expenses = data));

      axios
        .get("api/getAllExpensType")
        .then(({ data }) => (this.ExpensesType = data));
      this.tblData = $("#datatable1").DataTable({
        processing: true,
        serverSide: true,
        language: {
          url: "/gent/Persian.json"
        },
        ajax: {
          url: "api/getAllExpense",
          type: "POST"
        },
        columns: [
          { data: "id" },
          {
            data: "typeName",
            render: function(data) {
              if (data != null) {
                return data;
              } else {
                return "Not Found";
              }
            }
          },
          { data: "date" },
          { data: "amount" },
          { data: "description" },
          {
            data: "id",
            render: function(data, type, row) {
              var editButton =
                '<a href="#" class="btn btn-info btn-xs" onclick="editModal(' +
                row.id +
                ')"> <i class="fa fa-pencil"></i> سمول</a>';
              var deleteButton =
                '<a href="#" class="btn btn-danger btn-xs" onclick="deleteExpense(' +
                row.id +
                ')">  <i class="fa fa-trash-o"></i> ړنګول</a>';
              return editButton + deleteButton;
            }
          }
        ]
      });
      this.$Progress.finish();
    },

    createExpense() {
      if (this.form.expens_type_id == "") {
        toast.fire({
          icon: "warning",
          html: "<h5>د لکښت ډول اړین دی.</h5>"
        });
      } else if (this.form.amount == "") {
        toast.fire({
          icon: "warning",
          html: "<h5>پیسی  اړین دی.</h5>"
        });
      } else if (this.form.date == "") {
        toast.fire({
          icon: "warning",
          html: "<h5>نیټه  اړین ده.</h5>"
        });
      } else {
        this.form
          .post("api/Expense")
          .then(() => {
            $("#addNew").modal("hide");
            toast.fire({
              icon: "success",
              type: "success",
              html: "<h5> معلومات په بریالیتوب سره خوندي شول</h5>"
            });
            Fire.$emit("refreshPage");
            this.form.reset();
          })
          .catch(er => {
            console.log(er);
          });
      }
    }
  },
  created() {
    $.ajaxSetup({
      headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
      }
    });
    window.deleteExpense = this.deleteExpense;
    window.editModal = this.editModal;
  },
  mounted() {
    this.loadExpenses();

    // load the page after 3 secound
    Fire.$on("refreshPage", () => {
      this.tblData.ajax.reload();
      //this.loadExpenses();
    });
  }
};
</script>

Контроллер расходов

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Expenses;
use Illuminate\Support\Facades\Hash;
class ExpensesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
        $this->middleware('auth:api');
    }
    public function index()
    {
        try {
            $Expenses = Expenses::orderBy('date', 'ASC')->paginate(15);
            return response()->json($Expenses);
        } catch (Exception $e) {
            return response()->json($e->getMessage(), 500);
        }
    }

    public function getExpenseByid(Request $request)
    {
        $myId = '0';
        if ($request->has('id')) {
            $myId = $request->input('id');
        }

        try {
            $Expenses = Expenses::where('id', $myId)->get();
            return response()->json($Expenses);
        } catch (Exception $e) {
            return response()->json($e->getMessage(), 500);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        try {
            $this->validate($request, [
                'date' => 'required',
                'amount' => 'required',
                'expens_type_id' => 'required'
            ]);
            $Expenses = Expenses::create([
                'expens_type_id' => $request['expens_type_id'],
                'date' => $request['date'],
                'amount' => $request['amount'],
                'description' => $request['description']
            ]);
            return response()->json($Expenses);
        } catch (Exception $e) {
            return response()->json($e->getMessage(), 500);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        try {
            $Expenses = Expenses::findOrFail($id);
            $this->validate($request, [
                // 'Company'=>"required|string|unique:companies,Company,$id",
                'date' => 'required',
                'amount' => 'required',
                'expens_type_id' => 'required'
            ]);
            $Expenses->update($request->all());
            // return ['message'=>'Expenses info Updated Successfully'];
            //          return response()->json($Expenses);
        } catch (Exception $e) {
            return response()->json($e->getMessage(), 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function getAll(Request $request)
    {
        //Getting all posted data from datatable

        //this is just for dataTable and sending back as it is
        $draw = $request->draw;

        //how many records should be skipped (starting from zero means skip nothing)
        $skip = $request->start;

        //how many records should be taken
        $limit = $request->length;

        //The search string entered into datatable's search box
        $searchString = $request->search['value'];

        //The column index on which user clicked to order (starting from 0 means first column)
        $orderedColumnIndex = $request->order['0']['column'];

        //The direction of ordering of column (asc or desc)
        $direction = $request->order['0']['dir'];

        //The total records in database which should be sent to datatable
        $totalRecords = count(Expenses::all());
        $fileteredRecords = $totalRecords;
        try {
            $Expenses = Expenses::join(
                'expens_types',
                'expenses.expens_type_id',
                '=',
                'expens_types.id'
            );
            switch ($orderedColumnIndex) {
                case 1:
                    $Expenses = $Expenses->orderBy(
                        'expens_types.name',
                        $direction
                    );
                    break;
                case 2:
                    $Expenses = $Expenses->orderBy('expenses.date', $direction);
                    break;
                case 3:
                    $Expenses = $Expenses->orderBy(
                        'expenses.amount',
                        $direction
                    );
                    break;
                case 4:
                    $Expenses = $Expenses->orderBy(
                        'expenses.description',
                        $direction
                    );
                    break;
                default:
                    $Expenses = $Expenses->orderBy('expenses.id', $direction);
                    break;
            }

            $Expenses = $Expenses->select(
                'expenses.*',
                'expens_types.name as typeName'
            );

            if ($searchString != null) {
                $Expenses = $Expenses->where(function ($q) use ($searchString) {
                    $q
                        ->where(
                            'expenses.id',
                            'like',
                            '%' . $searchString . '%'
                        )
                        ->orWhere(
                            'expens_types.name',
                            'like',
                            '%' . $searchString . '%'
                        )
                        ->orWhere(
                            'expenses.date',
                            'like',
                            '%' . $searchString . '%'
                        )
                        ->orWhere(
                            'expenses.amount',
                            'like',
                            '%' . $searchString . '%'
                        )
                        ->orWhere(
                            'expenses.description',
                            'like',
                            '%' . $searchString . '%'
                        );
                });
            }

            if ($skip == 0) {
                $Expenses = $Expenses->take($limit)->get();
            } else {
                $Expenses = $Expenses
                    ->skip($skip)
                    ->take($limit)
                    ->get();
            }
            if ($searchString != null) {
                $fileteredRecords = count($Expenses);
            }
            $post_data = array(
                'draw' => $draw,
                'recordsTotal' => $totalRecords,
                'recordsFiltered' => $fileteredRecords,
                'data' => $Expenses
            );

            return response()->json($post_data);
        } catch (Exception $e) {
            return response()->json($e->getMessage(), 500);
        }
    }
    public function destroy($id)
    {
        try {
            $Expenses = Expenses::findOrFail($id);

            $Expenses->delete();
            return response()->json($Expenses);
        } catch (Exception $e) {
            return response()->json($e->getMessage(), 500);
        }

        //
    }

    public function multipledelete(Request $request)
    {
        try {
            $Expensess = Expenses::whereIn('id', $request->id)->get();
            foreach ($Expensess as $Expenses) {
                $Expenses->delete();
            }

            return response()->json('data deleted');
        } catch (Exception $e) {
            return response()->json($e->getMessage(), 500);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...