Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Datatables Editor Laravel Package

yajra/laravel-datatables-editor

Laravel plugin for yajra/laravel-datatables that handles server-side processing for DataTables Editor 2.x. Provides CRUD actions, validation, and Laravel 12.x integration for Editor-powered DataTables (premium Editor license required).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require yajra/laravel-datatables-editor:^13
    
  2. Publish assets (if using Laravel Mix/Vite):
    npm install datatables.net-dt
    npm install @datatables.net-editor
    
  3. Generate a DataTables Editor stub for your model (e.g., User):
    php artisan datatables:editor User
    
    This creates a controller (UserEditorController) with pre-configured CRUD methods.

First Use Case: Basic Inline Editing

  1. Define a DataTable with Editor:
    $(document).ready(function() {
        $('#user-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '/users-editor',
            columns: [
                { data: 'id', name: 'id' },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' },
                {
                    data: null,
                    name: 'action',
                    orderable: false,
                    searchable: false,
                    render: function(data, type, row) {
                        return `<a href="#" class="edit-row" data-id="${row.id}">Edit</a>`;
                    }
                }
            ],
            dom: 'lrtip',
            buttons: [
                { extend: 'editor', editor: {
                    ajax: {
                        newAction: '/users-editor/create',
                        editAction: '/users-editor/update',
                        removeAction: '/users-editor/destroy'
                    },
                    fields: [
                        { label: 'Name:', name: 'name' },
                        { label: 'Email:', name: 'email' }
                    ]
                }}
            ]
        });
    });
    
  2. Access the Editor endpoint via the generated controller (UserEditorController):
    public function anyDataTable()
    {
        return $this->datatables
            ->eloquent($this->query())
            ->make(true);
    }
    

Implementation Patterns

Core Workflows

1. CRUD Operations

  • Create/Update/Delete: Use the create, update, and destroy methods in the generated controller:
    public function anyCreate()
    {
        return $this->editor->create();
    }
    
    public function anyUpdate()
    {
        return $this->editor->update();
    }
    
    public function anyDestroy()
    {
        return $this->editor->destroy();
    }
    
  • Bulk Actions: Leverage the bulk method for mass updates/deletes:
    public function anyBulk()
    {
        return $this->editor->bulk();
    }
    

2. Validation

  • Define rules in the getRules() method of your editor controller:
    protected function getRules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,'.$this->getKey().',id',
        ];
    }
    
  • Custom Validation: Override validate() for complex logic:
    protected function validate($request)
    {
        $validator = Validator::make($request->all(), $this->getRules());
        if ($validator->fails()) {
            return $this->editor->jsonResponse($validator->errors()->all(), 422);
        }
        return true;
    }
    

3. Event Hooks

  • Use pre/post hooks for side effects (e.g., logging, notifications):
    protected function beforeCreate($request)
    {
        // Example: Log creation
        \Log::info('User created via DataTables Editor', $request->all());
    }
    
    protected function afterUpdate($request, $model)
    {
        // Example: Send email
        Mail::to($model->email)->send(new UserUpdated($model));
    }
    
  • Custom Events: Dispatch Laravel events:
    protected function afterSave($request, $model)
    {
        event(new UserSaved($model));
    }
    

4. Custom Actions

  • Extend functionality with customActions:
    protected function getCustomActions()
    {
        return [
            'custom_action' => [
                'label' => 'Custom Action',
                'action' => 'customAction',
                'buttonClass' => 'btn btn-warning',
            ],
        ];
    }
    
    public function customAction()
    {
        $data = $this->editor->getData();
        // Custom logic (e.g., API call, file processing)
        return $this->editor->jsonResponse(['success' => true]);
    }
    

5. File Uploads

  • Handle file uploads in storeUploadedFile:
    protected function storeUploadedFile($field, UploadedFile $uploadedFile)
    {
        $path = $uploadedFile->store('uploads', $this->getDisk());
        return $path;
    }
    
    protected function getUploadDirectory()
    {
        return 'uploads';
    }
    
    protected function getDisk()
    {
        return \Storage::disk('public');
    }
    

Integration Tips

  • API Routes: Route Editor actions to the controller:
    Route::prefix('users-editor')->group(function () {
        Route::any('/', [UserEditorController::class, 'anyDataTable']);
        Route::any('create', [UserEditorController::class, 'anyCreate']);
        Route::any('update', [UserEditorController::class, 'anyUpdate']);
        Route::any('destroy', [UserEditorController::class, 'anyDestroy']);
        Route::any('bulk', [UserEditorController::class, 'anyBulk']);
    });
    
  • Blade Integration: Embed the DataTable in a view:
    <table id="user-table" class="display" style="width:100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Actions</th>
            </tr>
        </thead>
    </table>
    
  • Testing: Use Laravel’s HTTP tests to simulate Editor requests:
    public function test_create_user_via_editor()
    {
        $response = $this->postJson('/users-editor/create', [
            'name' => 'Test User',
            'email' => 'test@example.com',
        ]);
        $response->assertStatus(200);
        $this->assertDatabaseHas('users', ['email' => 'test@example.com']);
    }
    

Gotchas and Tips

Pitfalls

  1. Premium License Requirement:

    • The DataTables Editor library is premium-only. Ensure your team has a valid license before adoption.
    • Workaround: Use the free DataTables Buttons for basic CRUD if the budget is constrained.
  2. CSRF Token Mismatch:

    • Editor requests may fail with CSRF token mismatch if not handled properly.
    • Fix: Exclude Editor routes from CSRF verification in VerifyCsrfToken middleware:
      protected $except = [
          'users-editor/*',
      ];
      
    • Alternative: Use meta data in Editor initialization:
      editor: {
          meta: {
              csrf_token: '{{ csrf_token() }}'
          }
      }
      
  3. Model Key Conflicts:

    • If your model’s primary key is not id, override getKey():
      protected function getKey()
      {
          return $this->editor->getModel()->getKeyName();
      }
      
  4. Bulk Action Validation:

    • Bulk actions may return partial failures. Handle errors gracefully:
      public function anyBulk()
      {
          $response = $this->editor->bulk();
          if ($response->hasErrors()) {
              return $this->editor->jsonResponse([
                  'error' => 'Some records failed to update',
                  'errors' => $response->getErrors()
              ], 422);
          }
          return $response;
      }
      
  5. Nested Relations:

    • Editor does not natively support nested relations (e.g., hasMany). Use custom fields or server-side processing:
      fields: [
          {
              label: 'Orders:',
              name: 'orders',
              type: 'select',
              options: {
                  url: '/orders-dropdown',
                  cache: true
              }
          }
      ]
      
  6. Type Safety:

    • Laravel 12+ uses strict typing. Ensure your editor controller extends Yajra\DataTables\Editor\Editor and methods are typed:
      public function anyDataTable(): JsonResponse
      {
          return $this->datatables->eloquent($this->query())->make(true);
      }
      

Debugging Tips

  1. Log Editor Requests:
    • Add middleware to log Editor payloads:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony