带有服务器端的 Laravel 5 数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31008343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 datatables with server-side
提问by ruuux93
I'm trying to use datatablesplugin together with laravel since I need to manage large tables, and the laravel pagination won't be good enough.
我正在尝试将datatables插件与 laravel 一起使用,因为我需要管理大表,而 laravel 分页不够好。
I'm using yajra/laravel-datatablescomponent, but I can't get it to work, it throws an error:
我正在使用yajra/laravel-datatables组件,但我无法让它工作,它抛出一个错误:
DataTables warning: table id=project-table - Ajax error. Fore more information about this error, please see http://datatables.net/tn/7
数据表警告:表 id=project-table - Ajax 错误。有关此错误的更多信息,请参阅http://datatables.net/tn/7
After reading it, I don't know how to solve it, I'm pretty sure that it has something to do with my routing, because I don't quite understand how the ajax is fetching the result.
看了之后不知道怎么解决,很确定跟我的路由有关系,因为不太明白ajax是怎么获取结果的。
This is what I've done:
这就是我所做的:
routes.php
路由文件
Route::controllers([
'projects' => 'ProjectController'
]);
]);
ProjectController.php (just the function that fetch the data)
ProjectController.php(只是获取数据的函数)
public function getDataTable()
{
$projectes = Project::select(['id', 'nom', 'desc', 'preu', 'hores', 'created_at']);
return Datatables::of($projectes)->make(true);
}
The view:
风景:
<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>
Finally, the js:
最后,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'}
]
});
});
});
回答by BakerStreetSystems
Change your function to getDatatable
(make the T lowercase) in your ProjectController.php
. Then change the url in your ajax request to projects/datatable
(without the get
. Since you used a controller route, the controller will listen for a GET request at projects/datatable
).
将您的函数更改为getDatatable
(使 T 小写)ProjectController.php
。然后将 ajax 请求中的 url 更改为projects/datatable
(不带get
。由于您使用了控制器路由,因此控制器将在 处侦听 GET 请求projects/datatable
)。
If that doesn't do it, please post the response when you open the projects/datatable
page directly in your browser.
如果没有这样做,请在您projects/datatable
直接在浏览器中打开页面时发布响应。
回答by user6876923
Laravel 5.1 must be installed at the datatables version 6.0:
Laravel 5.1 必须安装在数据表 6.0 版上:
composer require yajra/laravel-datatables-oracle:~6.0
回答by Abdo-Host
DataTables Server-side Processing in Laravel
Laravel 中的 DataTables 服务器端处理
In this tutorial, I will show you the easiest way to implement DataTables jQuery Plugin with remote server side processing in Laravel. Here I will show you how to fetch data from remote MySQL database through ajax in Laravel. For those who don't here about Datatables, DataTables is a table enhancing plug-in for the jQuery Javascript library that helps in adding sorting, paging and filtering abilities to plain HTML tables with minimal effort. The main goal is to enhance the accessibility of data in normal HTML tables.
在本教程中,我将向您展示在 Laravel 中使用远程服务器端处理实现 DataTables jQuery 插件的最简单方法。在这里我将向您展示如何在 Laravel 中通过 ajax 从远程 MySQL 数据库中获取数据。对于那些不了解 Datatables 的人来说,DataTables 是一个用于 jQuery Javascript 库的表格增强插件,它有助于以最少的努力为纯 HTML 表格添加排序、分页和过滤功能。主要目标是增强普通 HTML 表格中数据的可访问性。
Now before we start coding include Datatables CSS file and Javascript files from CDN in your view page as follows.
现在在我们开始编码之前,在您的视图页面中包含 Datatables 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>
Now let's understand what all tasks we need to do
现在让我们了解我们需要做的所有任务
- We need to limit the size of the table. (By default 10,25,50 or 100 entries)
- Now Implement search functionality.
- The Pagination task.
- 我们需要限制表的大小。(默认为 10、25、50 或 100 个条目)
- 现在实现搜索功能。
- 分页任务。
All above task will be done in the controller and it will be explained later in this tutorial.
以上所有任务都将在控制器中完成,本教程稍后将对其进行解释。
Now let's start coding.
现在让我们开始编码。
In the view page code for HTML table is given below.
下面给出了 HTML 表格的视图页面代码。
<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>
The javascript code is given below.
下面给出了 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.
注意:不要忘记将 CSRF 令牌与上述 ajax POST 请求一起传递。否则会出现内部服务器错误500。这是因为 Laravel 默认在所有 POST 控制器函数中检查 CSRF 令牌以确保最大程度的保护。
Now the code for post routes in routes/web.php
现在在 routes/web.php 中发布路由的代码
Route::post('allposts', 'PostController@allPosts' )->name('allposts');
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
}
Now the code for allPost function in PostController.
现在是 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'] = " <a href='{$show}' title='SHOW' ><span class='glyphicon glyphicon-list'></span></a>
 <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);
}