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

Admin Generator Bundle Laravel Package

carlespibernat/admin-generator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require carlespibernat/admin-generator-bundle
    

    Register the bundle in config/app.php under providers:

    Carlespibernat\AdminGeneratorBundle\CarlespibernatAdminGeneratorBundle::class,
    
  2. Configuration Publish the default config:

    php artisan admin-generator:install
    

    Update config/admin_generator.php to match your needs (e.g., default_namespace, model_namespace).

  3. First Use Case Generate a CRUD for an existing model (e.g., User):

    php artisan admin-generator:generate User
    

    This creates:

    • A controller (UserAdminController).
    • Views (index.html.twig, edit.html.twig, etc.) in resources/views/admin/user/.
    • Routes in routes/admin.php.
  4. Access the Admin Panel Visit /admin/user (or your configured route prefix). Authenticate via your existing auth system (e.g., Symfony Guard or Laravel’s built-in auth).


Implementation Patterns

Workflows

  1. Model-Driven Generation

    • Generate from Scratch: Use php artisan admin-generator:generate ModelName to scaffold a full CRUD.
    • Regenerate: Overwrite existing files with --force:
      php artisan admin-generator:generate User --force
      
    • Partial Generation: Generate only a controller or views:
      php artisan admin-generator:generate User --only=controller
      
  2. Customization

    • Override Templates: Copy the default Twig templates from vendor/carlespibernat/admin-generator-bundle/resources/views/ to resources/views/admin/ to customize them globally.
    • Per-Entity Overrides: Place custom templates in resources/views/admin/{entity_name}/ (e.g., resources/views/admin/user/edit.html.twig).
    • Controller Extensions: Extend the generated controller:
      namespace App\Admin;
      use Carlespibernat\AdminGeneratorBundle\Admin\AbstractAdminController;
      
      class UserAdminController extends AbstractAdminController
      {
          public function customize()
          {
              $this->addField('custom_field', 'text');
          }
      }
      
  3. Integration with Laravel

    • Authentication: Use Laravel’s auth middleware in routes/admin.php:
      Route::group(['middleware' => ['auth']], function () {
          $this->loadRoutesFrom(__DIR__.'/admin_routes.php');
      });
      
    • Authorization: Implement policy checks in the controller’s authorize() method or use Laravel’s gates/policies.
    • Form Requests: Replace the default form handling with Laravel’s FormRequest:
      use App\Http\Requests\StoreUserRequest;
      
      public function store(StoreUserRequest $request)
      {
          // Custom validation/logic
      }
      
  4. Dynamic Fields

    • Add fields dynamically in the controller’s customize() method:
      public function customize()
      {
          $this->addField('active', 'boolean', [
              'label' => 'Is Active',
              'editable' => true,
          ]);
      }
      
    • Support for relationships:
      $this->addAssociation('roles', 'belongsToMany', 'Role');
      
  5. API Endpoints

    • Generate API-only CRUDs by passing --api:
      php artisan admin-generator:generate User --api
      
    • Extend API responses using Laravel’s Resource classes or custom JSON logic.

Integration Tips

  • Laravel Mix/Webpack: Ensure your webpack.mix.js compiles assets for the admin namespace if using custom JS/CSS.
  • Translation: Use Laravel’s translation system (lang/ directory) for labels/buttons. Override the bundle’s translations in config/admin_generator.php:
    'translations' => [
        'default_locale' => 'en',
        'paths' => [__DIR__.'/../resources/lang'],
    ],
    
  • Database Migrations: Run migrations after generating models to ensure tables exist:
    php artisan migrate
    
  • Testing: Use Laravel’s testing helpers to assert admin routes:
    $this->get('/admin/user')->assertStatus(200);
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • Ensure default_namespace in config/admin_generator.php matches your Laravel app’s namespace (e.g., App\Admin).
    • Avoid naming collisions with existing controllers/models.
  2. Route Caching

    • Clear route cache after generating new routes:
      php artisan route:clear
      
    • Or disable caching in config/admin_generator.php:
      'route_cache' => false,
      
  3. Twig vs. Blade

    • The bundle uses Twig by default. For Blade templates:
      • Install tightenco/jigsaw or manually convert Twig templates.
      • Override the template engine in the controller:
        protected $templateEngine = 'blade';
        
  4. Model Not Found

    • Ensure the model exists and is in the correct namespace (e.g., App\Models\User). The generator skips non-existent models silently.
  5. CSRF Token Mismatch

    • If using Laravel’s session driver, ensure the admin routes are under the same domain/subdomain as your app to avoid CSRF issues.
  6. Asset Paths

    • Custom CSS/JS paths in templates must use Laravel’s asset() helper or absolute URLs to avoid 404s.

Debugging

  1. Generator Logs

    • Enable verbose output:
      php artisan admin-generator:generate User --verbose
      
    • Check storage/logs/laravel.log for errors.
  2. Template Debugging

    • Enable Twig debug mode in config/admin_generator.php:
      'twig' => [
          'debug' => env('APP_DEBUG', true),
      ],
      
    • Use Twig’s dump() function in templates for debugging.
  3. Route Debugging

    • List all admin routes:
      php artisan route:list --path=/admin
      
    • Test routes individually with php artisan route:test.
  4. Database Issues

    • Verify the model’s table exists and matches the model’s $table property. Use:
      php artisan schema:dump
      
      to inspect the schema.

Tips

  1. Partial Regeneration

    • Regenerate only the views for an entity:
      php artisan admin-generator:generate User --only=views
      
  2. Multi-Tenant Support

    • Extend the controller to add tenant-aware logic:
      public function customize()
      {
          $this->addFilter('tenant_id', 'number', [
              'label' => 'Tenant ID',
              'value' => auth()->user()->tenant_id,
          ]);
      }
      
  3. Soft Deletes

    • Enable soft deletes in the model and customize the admin to handle them:
      public function customize()
      {
          $this->addField('deleted_at', 'datetime', [
              'editable' => false,
              'label' => 'Deleted At',
          ]);
      }
      
  4. Bulk Actions

    • Add bulk actions via the customize() method:
      public function customize()
      {
          $this->addBulkAction('delete', 'Delete Selected', 'deleteBulk');
      }
      
      public function deleteBulk(Request $request)
      {
          $this->model->whereIn('id', $request->input('ids'))->delete();
          return redirect()->back()->with('success', 'Items deleted');
      }
      
  5. Search/Filter Optimization

    • Customize search/filter queries in the controller:
      public function getListQuery()
      {
          return $this->model->where('active', true);
      }
      
  6. Localization

    • Override translations per entity by creating a translations.php file in the entity’s directory (e.g., resources/admin/user/translations.php):
      return [
          'buttons' => [
              'save' => 'Guardar Cambios',
          ],
      ];
      
  7. Performance

    • Use eager loading for relationships in the getList() method:
      public function getList()
      {
          return $this->model->with('roles')->get();
      }
      
    • Paginate results:
      return $this->model->paginate(20);
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware