首页 > 解决方案 > 如何正确结合 laravel 和数据表编辑器

问题描述

告诉我如何将服务器端数据表脚本添加到我通过 ajax 访问的控制器方法中,以便可以通过路由访问它。其他一切似乎都是正确的。但我不知道如何在 laravel 中正确地做服务器端。我试图将数据表后端添加到控制器方法中。变量 $ db 必须是全局的,也许这是错误的,我不知道。并得到以下错误。另外我认为路由也需要修复,但我不知道如何。

路线

Route::get('/service/formats', [FormatController::class, 'index'])->name('service.formats');
Route::get('/service/formats/load', [FormatController::class, 'getAllJson'])->name('service.formats.getall');

控制器

    <?php

namespace App\Http\Controllers;

use App\Models\Format;
use DataTables\Editor;
use DataTables\Editor\Field;
use Illuminate\Http\Request;


class FormatController extends Controller
{
    public function index()
    {
        return view('service.format.index');
    }

    public function getAllJson()
    {
        global $db;
        Editor::inst($db, 'formats', 'id')
            ->fields(
                Field::inst('id'),
                Field::inst('name')
            )
            ->process($_POST)
            ->json();
    }


}

js

<script>
    var editor; // use a global for the submit and return data rendering in the examples

    $(document).ready(function() {
        editor = new $.fn.dataTable.Editor( {
            ajax: "{{ route('service.formats.getall') }}",
            table: "#formats",
            fields: [ {
                label: "ID:",
                name: "ID"
            }, {
                label: "Name:",
                name: "Name"
            }
            ]
        } );

        $('#formats').DataTable( {
            dom: "Bfrtip",
            ajax: "{{ route('service.formats.getall') }}",
            columns: [
                { data: "ID" },
                { data: "Name" }
            ],
            select: true,
            buttons: [
                { extend: "create", editor: editor },
                { extend: "edit",   editor: editor },
                { extend: "remove", editor: editor }
            ]
        } );
    } );
</script>

错误

{
"message": "Call to a member function transaction() on null",
"exception": "Error",
"file": "/application/vendor/datatables.net/editor-php/Editor.php",
"line": 969,
"trace": [
    {
        "file": "/application/vendor/datatables.net/editor-php/Editor.php",
        "line": 701,
        "function": "_process",
        "class": "DataTables\\Editor",
        "type": "->"
    },
    {
        "file": "/application/app/Http/Controllers/FormatController.php",
        "line": 26,
        "function": "process",
        "class": "DataTables\\Editor",
        "type": "->"
    },
    {
        "file": "/application/vendor/laravel/framework/src/Illuminate/Routing/Controller.php",
        "line": 54,
        "function": "getAllJson",
        "class": "App\\Http\\Controllers\\FormatController",
        "type": "->"
    },
    .....and that is not all

标签: phplaraveldatatables

解决方案


推荐阅读