Laravel 5 带有服务器端的数据表

Laravel 5 datatables with server-side

我正在尝试将 datatables 插件与 laravel 一起使用,因为我需要管理大型表格,而 laravel 分页不够好。

我正在使用 yajra/laravel-datatables 组件,但我无法让它工作,它抛出一个错误:

DataTables warning: table id=project-table - Ajax error. Fore more information about this error, please see http://datatables.net/tn/7

看完了,不知道怎么解决,我很确定和我的路由有关系,因为我不太明白ajax是怎么取的结果。

这是我所做的:

routes.php

Route::controllers([
'projects'       => 'ProjectController'

]);

ProjectController.php(就是获取数据的函数)

    public function getDataTable()
{
    $projectes = Project::select(['id', 'nom', 'desc', 'preu', 'hores', 'created_at']);

    return Datatables::of($projectes)->make(true);
}

观点:

<table id="project-table" class="table table-condensed table-bordered table-striped">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Titol</th>
                        <th>Desc</th>
                        <th>Preu</th>
                        <th>Hores</th>
                        <th>Data Alta</th>
                    </tr>
                </thead>
            </table>

最后,js:

$(function() {
$('#project-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '{{ url("projects/getDataTable") }}',
    columns: [
        {data: 'id', name: 'id'},
        {data: 'nom', name: 'nom'},
        {data: 'desc', name: 'desc'},
        {data: 'preu', name: 'preu'},
        {data: 'hores', name: 'hores'},
        {data: 'created_at', name: 'created_at'}
    ]
});

});

ProjectController.php 中的函数更改为 getDatatable(将 T 变为小写)。然后将 ajax 请求中的 url 更改为 projects/datatable(不带 get。由于您使用了控制器路由,控制器将在 [=12] 处侦听 GET 请求=]).

如果还是不行,请 post 直接在浏览器中打开 projects/datatable 页面时的响应。

Laravel 5.1 必须安装在数据表版本 6.0:

composer require yajra/laravel-datatables-oracle:~6.0

DataTables 服务器端处理 Laravel

在本教程中,我将向您展示在 Laravel 中使用远程服务器端处理实现 DataTables jQuery 插件的最简单方法。在这里,我将向您展示如何通过 Laravel 中的 ajax 从远程 MySQL 数据库中获取数据。对于那些不了解 Datatables 的人,DataTables 是 jQuery Javascript 库的 table 增强插件,有助于添加排序、分页和过滤能够以最小的努力来解释 HTML tables。主要目标是提高正常 HTML tables.

中数据的可访问性

现在,在我们开始编码之前,在您的视图页面中包含数据tables CSS 文件和来自 CDN 的 Javascript 文件,如下所示。

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.css"/>

<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.js"></script>

现在让我们了解一下我们需要完成的所有任务

  1. 我们需要限制 table 的大小。 (默认为 10、25、50 或 100 条目)
  2. 现在实现搜索功能。
  3. 分页任务。

以上所有任务都将在控制器中完成,本教程稍后将对此进行解释。

现在让我们开始编码。

HTML table 的查看页面代码如下。

 <div class="row">
<div class="col-md-12">
           <table class="table table-bordered" id="posts">
                <thead>
                       <th>Id</th>
                       <th>Title</th>
                       <th>Body</th>
                       <th>Created At</th>
                       <th>Options</th>
                </thead>                
           </table>
    </div>

javascript代码如下。

script>
$(document).ready(function () {
    $('#posts').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax":{
                 "url": "{{ url('allposts') }}",
                 "dataType": "json",
                 "type": "POST",
                 "data":{ _token: "{{csrf_token()}}"}
               },
        "columns": [
            { "data": "id" },
            { "data": "title" },
            { "data": "body" },
            { "data": "created_at" },
            { "data": "options" }
        ]    

    });
});

Note: Do not forget to pass CSRF Token along with ajax POST request as above. Otherwise, internal server error 500 will occur. This is because Laravel checks CSRF token in all POST controller functions by default to ensure maximum protection.

现在 routes/web 中 post 路线的代码。php

Route::post('allposts', 'PostController@allPosts' )->name('allposts');


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

}

现在是 PostController 中 allPost 函数的代码。

public function allPosts(Request $request)
    {

        $columns = array( 
                            0 =>'id', 
                            1 =>'title',
                            2=> 'body',
                            3=> 'created_at',
                            4=> 'id',
                        );

        $totalData = Post::count();

        $totalFiltered = $totalData; 

        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');

        if(empty($request->input('search.value')))
        {            
            $posts = Post::offset($start)
                         ->limit($limit)
                         ->orderBy($order,$dir)
                         ->get();
        }
        else {
            $search = $request->input('search.value'); 

            $posts =  Post::where('id','LIKE',"%{$search}%")
                            ->orWhere('title', 'LIKE',"%{$search}%")
                            ->offset($start)
                            ->limit($limit)
                            ->orderBy($order,$dir)
                            ->get();

            $totalFiltered = Post::where('id','LIKE',"%{$search}%")
                             ->orWhere('title', 'LIKE',"%{$search}%")
                             ->count();
        }

        $data = array();
        if(!empty($posts))
        {
            foreach ($posts as $post)
            {
                $show =  route('posts.show',$post->id);
                $edit =  route('posts.edit',$post->id);

                $nestedData['id'] = $post->id;
                $nestedData['title'] = $post->title;
                $nestedData['body'] = substr(strip_tags($post->body),0,50)."...";
                $nestedData['created_at'] = date('j M Y h:i a',strtotime($post->created_at));
                $nestedData['options'] = "&emsp;<a href='{$show}' title='SHOW' ><span class='glyphicon glyphicon-list'></span></a>
                                          &emsp;<a href='{$edit}' title='EDIT' ><span class='glyphicon glyphicon-edit'></span></a>";
                $data[] = $nestedData;

            }
        }

        $json_data = array(
                    "draw"            => intval($request->input('draw')),  
                    "recordsTotal"    => intval($totalData),  
                    "recordsFiltered" => intval($totalFiltered), 
                    "data"            => $data   
                    );

        echo json_encode($json_data); 

    }