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

Tablar Crud Generator Laravel Package

takielias/tablar-crud-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require takielias/tablar-crud-generator
    

    Publish the config file:

    php artisan vendor:publish --provider="Takielias\TablarCrudGenerator\TablarCrudGeneratorServiceProvider"
    
  2. Generate a CRUD: Run the generator for an existing model (e.g., User):

    php artisan tablar:crud User
    

    This creates:

    • A Tablar-based CRUD controller (app/Http/Controllers/UserCrudController.php).
    • A Blade view (resources/views/tablar/crud/user/index.blade.php).
    • Optional: A migration (if --migration flag is used).
  3. First Use Case: Access the CRUD via a route (auto-generated in routes/web.php):

    Route::resource('users', UserCrudController::class)->shallow();
    

    Visit /users to see the auto-generated CRUD interface.


Key Configuration

  • Config File: config/tablar-crud-generator.php
    • Define default table names, view paths, and model relationships.
    • Example:
      'views' => [
          'path' => 'resources/views/tablar/crud',
          'namespace' => 'Tablar\Crud',
      ],
      

Initial Workflow

  1. Generate CRUD:

    php artisan tablar:crud Post --migration --seed
    
    • --migration: Creates a migration for the model.
    • --seed: Seeds the database with test data.
  2. Customize Routes: Override the auto-generated route in routes/web.php:

    Route::prefix('admin')->name('admin.')->group(function () {
        Route::resource('posts', PostCrudController::class)->shallow();
    });
    
  3. Extend the Controller: Modify the generated PostCrudController to add custom logic:

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
        ]);
    
        // Custom logic before saving
        $post = Post::create($validated);
    
        // Custom logic after saving
        event(new PostCreated($post));
    
        return redirect()->route('posts.index')->with('success', 'Post created!');
    }
    

Implementation Patterns

Core Workflows

1. Generating CRUDs for Multiple Models

Use a loop in a script or composer.json post-install script:

php artisan tablar:crud User Product Category --migration
  • Batch Processing: Create a custom Artisan command to generate CRUDs for all models in a namespace:
    // app/Console/Commands/GenerateAllCruds.php
    public function handle()
    {
        $models = app()->make('Illuminate\Contracts\Foundation\Application')
            ->getNamespace() . '\App\Models\\';
    
        $files = File::files(app_path('Models'));
        foreach ($files as $file) {
            $class = 'App\Models\\' . str_replace('.php', '', basename($file));
            if (is_subclass_of($class, Model::class)) {
                $this->call('tablar:crud', ['model' => class_basename($class), '--migration' => true]);
            }
        }
    }
    

2. Reusing CRUD Logic Across Projects

  • Shared Config: Store custom configurations in a shared package or repository.
  • Base Controller: Extend the generated controller with a base class:
    // app/Http/Controllers/BaseCrudController.php
    abstract class BaseCrudController extends \Takielias\TablarCrudGenerator\Http\Controllers\CrudController
    {
        public function index()
        {
            $this->authorize('view', $this->model);
            return parent::index();
        }
    }
    
    Then, in your PostCrudController:
    class PostCrudController extends BaseCrudController
    {
        // ...
    }
    

3. Integrating with Existing Views

  • Partial Overrides: Override specific parts of the generated views (e.g., _form.blade.php) by placing custom files in the same directory structure:
    resources/
    └── views/
        └── tablar/
            └── crud/
                └── post/
                    ├── index.blade.php       // Overrides full index view
                    └── partials/
                        └── _form.blade.php   // Overrides form partial
    
  • Layout Wrapping: Use Blade @extends and @section directives in the generated views to integrate with your existing layouts.

4. Dynamic CRUD Generation

  • API-Driven CRUDs: Generate CRUDs dynamically based on API responses or database schemas:
    public function generateCrudFromSchema()
    {
        $schema = Schema::getConnection()->getDoctrineSchemaManager()->listTableDetails('posts');
        $columns = collect($schema->getTable('posts')->getColumns())->pluck('name');
    
        $this->call('tablar:crud', [
            'model' => 'Post',
            'fields' => $columns->implode(',')
        ]);
    }
    

Integration Tips

1. Laravel Mix/Webpack

  • Asset Compilation: Ensure your webpack.mix.js includes stylesheets for Tablar (e.g., DataTables):
    mix.postCss('resources/css/app.css', 'public/css', [
        require('postcss-import'),
        require('tailwindcss'),
    ]);
    
  • Custom CSS/JS: Override Tablar’s assets by publishing and modifying them:
    php artisan vendor:publish --tag=tablar-assets
    

2. Authentication & Authorization

  • Gate Policies: Protect CRUD actions using Laravel’s gates/policies:
    // app/Policies/PostPolicy.php
    public function viewAny(User $user)
    {
        return $user->hasRole('admin');
    }
    
    Then, in your controller:
    public function index()
    {
        $this->authorize('viewAny', $this->model);
        return parent::index();
    }
    

3. Testing

  • Feature Tests: Test CRUD routes using Laravel’s testing helpers:
    public function test_crud_operations()
    {
        $response = $this->get('/posts');
        $response->assertStatus(200);
    
        $response = $this->post('/posts', ['title' => 'Test', 'content' => 'Body']);
        $response->assertRedirect('/posts');
    
        $this->assertDatabaseHas('posts', ['title' => 'Test']);
    }
    
  • Factories: Use model factories to seed test data:
    Post::factory()->create(['title' => 'Test Post']);
    

4. Localization

  • Language Files: Override Tablar’s language strings in resources/lang/en/crud.php:
    return [
        'create' => 'Add New',
        'edit' => 'Modify',
        'delete' => 'Remove',
    ];
    

Gotchas and Tips

Pitfalls

1. Model Not Found Errors

  • Cause: The generator assumes the model exists in app/Models/. If the model is in a sub-namespace (e.g., App\Models\Admin\Post), specify the full namespace:
    php artisan tablar:crud "App\Models\Admin\Post"
    
  • Fix: Ensure the model is autoloaded or use the fully qualified class name.

2. Route Conflicts

  • Cause: Auto-generated routes may conflict with existing routes (e.g., /users vs. /admin/users).
  • Fix: Explicitly define routes in routes/web.php:
    Route::prefix('admin')->name('admin.')->group(function () {
        Route::resource('posts', PostCrudController::class)->shallow();
    });
    

3. View Override Issues

  • Cause: Custom view files in resources/views/tablar/crud/ may not override the generated views if the directory structure doesn’t match exactly.
  • Fix: Mirror the generated view structure:
    resources/
    └── views/
        └── tablar/
            └── crud/
                └── post/          // Must match the model name (lowercase)
                    ├── index.blade.php
                    └── create.blade.php
    

4. Migration Conflicts

  • Cause: Running --migration may create a migration that conflicts with an existing one.
  • Fix: Use --force to overwrite or manually merge migrations:
    php artisan tablar:crud User --migration --force
    

5. **Relationship

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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope