如何在 Laravel 7 中使用 DataTables 創建 AJAX 分頁

DataTables 是一個用於創建分頁的 jQuery 庫。它具有各種功能——分頁、排序​​、搜索等。

您可以使用和不使用AJAX加載數據。

在本教程中,我將展示如何使用 Laravel 7 中的 DataTables 創建具有搜索和排序功能的 AJAX 分頁。

我沒有為 DataTables 使用 Laravel 包。


1.創建表

  • Employees使用遷移創建一個新表並添加一些記錄。
php artisan make:migration create_employees_table
  • database/migration/現在,從項目根目錄導航到文件夾。
  • 找到一個以 結尾的 PHP 文件create_employees_table並打開它。
  • 在方法中定義表結構up()
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('username');
       $table->string('name');
       $table->string('email');
       $table->timestamps();
    });
}
  • 運行遷移 -
php artisan migrate
  • 表已創建並在其中添加一些記錄。

2. 下載

  • 從這裡下載 DataTables 庫 並下載 jQuery 庫。
  • 提取文件public/夾中下載的文件。
  • 此外,將 jQuery 庫複製到public/文件夾中。

3. 型號

  • 創建Employees模型。
php artisan make:model Employees
  • 使用該屬性指定可批量分配的模型屬性 - 用戶名、姓名和電子郵件$filliable

完成的代碼

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{

   protected $fillable = [
      'username','name','email' 
   ];

}

4. 路線

  • 打開routes/web.php文件。
  • 定義 2 條路線 –
Route::get('/','EmployeesController@index');
Route::get('/employees/getEmployees/','EmployeesController@getEmployees')->name('employees.getEmployees');
  • 第二條路由用於 AJAX 請求。

5.控制器

  • 創建 EmployeesController 控制器。
php artisan make:controller EmployeesController
  • 打開 app/Http/Controllers/EmployeesController.php 文件。
  • 導入 Employees 模型。
  • 創建兩個方法——
    • index() - 加載 employees.index 視圖。
    • getEmployees() -用於處理 DataTable AJAX 請求。

讀取數據表發送的值並存儲在變量中。

計算有和沒有搜索過濾器的總記錄並在變量中分配。

employees從表中獲取記錄。用於$searchValue搜索name字段、$start輸入skip()$rowperpage輸入take()以限制獲取的記錄數。

在 DataTables 初始化時,循環獲取的記錄並 使用選項$data_arr中定義的類似鍵初始化 Array 。columns

$response 使用 draw、iTotalRecords、iTotalDisplayRecords 和 aaData 鍵初始化 Array。

以 JSON 格式返回$response數組。

完成的代碼

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Employees;

class EmployeesController extends Controller{

   public function index(){
      return view('employees.index'); 
   }

   /*
   AJAX request
   */
   public function getEmployees(Request $request){

     ## Read value
     $draw = $request->get('draw');
     $start = $request->get("start");
     $rowperpage = $request->get("length"); // Rows display per page

     $columnIndex_arr = $request->get('order');
     $columnName_arr = $request->get('columns');
     $order_arr = $request->get('order');
     $search_arr = $request->get('search');

     $columnIndex = $columnIndex_arr[0]['column']; // Column index
     $columnName = $columnName_arr[$columnIndex]['data']; // Column name
     $columnSortOrder = $order_arr[0]['dir']; // asc or desc
     $searchValue = $search_arr['value']; // Search value

     // Total records
     $totalRecords = Employees::select('count(*) as allcount')->count();
     $totalRecordswithFilter = Employees::select('count(*) as allcount')->where('name', 'like', '%' .$searchValue . '%')->count();

     // Fetch records
     $records = Employees::orderBy($columnName,$columnSortOrder)
       ->where('employees.name', 'like', '%' .$searchValue . '%')
       ->select('employees.*')
       ->skip($start)
       ->take($rowperpage)
       ->get();

     $data_arr = array();
     
     foreach($records as $record){
        $id = $record->id;
        $username = $record->username;
        $name = $record->name;
        $email = $record->email;

        $data_arr[] = array(
          "id" => $id,
          "username" => $username,
          "name" => $name,
          "email" => $email
        );
     }

     $response = array(
        "draw" => intval($draw),
        "iTotalRecords" => $totalRecords,
        "iTotalDisplayRecords" => $totalRecordswithFilter,
        "aaData" => $data_arr
     );

     echo json_encode($response);
     exit;
   }
}

6.查看

創建文件 –

  • employees 在 文件夾中創建一個新文件resources/views/夾。
  • 在 resources/views/employees/文件夾中創建一個新index.blade.php 文件。

包括 CSS 和 JS –

  • 在該部分包括 Datatables CSS、jQuery 和 Datatables JS <head > 。

HTML 表格 –

  • 創建<table id="empTable">.

腳本 -

  • 在 上初始化數據表#empTable
  • 設置處理:true,serverSide:true。
  • 發送 AJAX 請求到"{{route('employees.getEmployees')}}".
  • 在 columns 選項中指定在成功回調時讀取的鍵名。

完成的代碼

<!DOCTYPE html>
<html>
  <head>
    <title>Datatables AJAX pagination with Search and Sort - Laravel 7</title>

    <!-- Meta -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
   
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="{{asset('DataTables/datatables.min.css')}}">

    <!-- Script -->
    <script src="{{asset('jquery-3.6.0.min.js')}}" type="text/javascript"></script>
    <script src="{{asset('DataTables/datatables.min.js')}}" type="text/javascript"></script>


    <!-- Datatables CSS CDN -->
    <!-- <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"> -->

    <!-- jQuery CDN -->
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> -->

    <!-- Datatables JS CDN -->
    <!-- <script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script> -->

  </head>
  <body>

    <table id='empTable' width='100%' border="1" style='border-collapse: collapse;'>
      <thead>
        <tr>
          <td>S.no</td>
          <td>Username</td>
          <td>Name</td>
          <td>Email</td>
        </tr>
      </thead>
    </table>

    <!-- Script -->
    <script type="text/javascript">
    $(document).ready(function(){

      // DataTable
      $('#empTable').DataTable({
         processing: true,
         serverSide: true,
         ajax: "{{route('employees.getEmployees')}}",
         columns: [
            { data: 'id' },
            { data: 'username' },
            { data: 'name' },
            { data: 'email' },
         ]
      });

    });
    </script>
  </body>
</html>

7. 演示

查看演示


8. 結論

在視圖文件中初始化 DataTables 並處理來自控制器的 DataTables AJAX 請求。DataTables 響應必須採用指定的格式。

如果您的數據未加載到 DataTable 上,則從控制器對其進行調試。檢查是否定義了 datatables initialize 中 'columns' 選項中指定的所有鍵名,檢查 SQL 查詢。

來源:https ://makitweb.com

#laravel #php 

What is GEEK

Buddha Community

如何在 Laravel 7 中使用 DataTables 創建 AJAX 分頁

I am Developer

1597727551

Laravel 7 Crud using Datatables

yajra datatables crud with ajax in laravel 7. In this post, i will show you how to create crud using datatable in laravel with ajax and model.

Now, i am going to show you how to install and use datatables in laravel 7 application. i will use jquery ajax crud with modals using datatables js in laravel 7. i will write easy code of jquery ajax request for crud with yajra datatable.

Laravel 7 DataTable CRUD Example

Use the below steps and create yajra DataTables crud with ajax in laravel:

Step 1: Install Laravel App For DataTable Crud
Step 2: Configuration .evn file
Step 3: Run Migration
Step 4: Install Yajra DataTables Package
Step 5: Add Fake Data into Database table
Step 6: Add Datatable Ajax Route
Stpe 7: Create DataTableController
Step 8: Create Ajax Datatable Blade View
Step 9: Start Development Server

https://www.tutsmake.com/laravel-7-6-install-yajra-datatables-example-tutorial/

#laravel 6 yajra datatables #yajra datatables laravel 6 example #laravel-datatables crud #yajra datatables laravel 7 #laravel 7 datatables #yajra datatables laravel

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer

1593933651

Laravel 7 Ajax Dynamic Dependent Dropdown

In this tutorial i will share with you how to create dependent dropdown using ajax in laravel. Or how to create selected subcategories dropdown based on selected category dropdown using jQuery ajax in laravel apps.

As well as learn, how to retrieve data from database on onchange select category dropdown using jQuery ajax in drop down list in laravel.

Laravel Ajax Dynamic Dependent Dropdown Tutorial

Follow the below steps and implement dependent dropdown using jQuery ajax in laravel app:

  1. Step 1: Install Laravel New App
  2. Step 2: Add Database Details
  3. Step 3: Create Model and Migration
  4. Step 4: Add Routes
  5. Step 5: Create Controllers By Artisan
  6. Step 6: Create Blade Views
  7. Step 7: Run Development Server

Originally published at https://www.tutsmake.com/laravel-dynamic-dependent-dropdown-using-ajax-example

#laravel jquery ajax categories and subcategories select dropdown #jquery ajax dynamic dependent dropdown in laravel 7 #laravel dynamic dependent dropdown using ajax #display category and subcategory in laravel #onchange ajax jquery in laravel #how to make dynamic dropdown in laravel

How to Send E-mail Using Queue in Laravel 7/8

Today I will show you How to Send E-mail Using Queue in Laravel 7/8, many time we can see some process take more time to load like payment gateway, email send, etc. Whenever you are sending email for verification then it load time to send mail because it is services. If you don’t want to wait to user for send email or other process on loading server side process then you can use queue.

Read More : How to Send E-mail Using Queue in Laravel 7/8

https://websolutionstuff.com/post/how-to-send-e-mail-using-queue-in-laravel-7-8


Read Also : Send Mail Example In Laravel 8

https://websolutionstuff.com/post/send-mail-example-in-laravel-8

#how to send e-mail using queue in laravel 7/8 #email #laravel #send mail using queue in laravel 7 #laravel 7/8 send mail using queue #laravel 7/8 mail queue example

Laravel AJAX CRUD Example Tutorial

Hello Guys,

Today I will show you how to create laravel AJAX CRUD example tutorial. In this tutorial we are implements ajax crud operation in laravel. Also perform insert, update, delete operation using ajax in laravel 6 and also you can use this ajax crud operation in laravel 6, laravel 7. In ajax crud operation we display records in datatable.

Read More : Laravel AJAX CRUD Example Tutorial

https://www.techsolutionstuff.com/post/laravel-ajax-crud-example-tutorial


Read Also : Read Also : Laravel 6 CRUD Tutorial with Example

https://techsolutionstuff.com/post/laravel-6-crud-tutorial-with-example

#laravel ajax crud example tutorial #ajax crud example in laravel #laravel crud example #laravel crud example with ajax #laravel #php