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

Crud Laravel Package

laravel-admin/crud

Experimental Laravel package providing a ResourceController for quick CRUD admin modules. Define a model plus singular/plural names, add resource routes, and override methods to declare form fields, validation rules, and payload transforms. Includes Bootstrap-friendly views.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require laravel-admin/crud
    

    Add to config/app.php:

    LaravelAdmin\Crud\CrudServiceProvider::class,
    
  2. Create a Resource

    php artisan make:model Blog -mcr
    
    • Migrate (php artisan migrate)
    • Model (Blog.php)
    • Controller (BlogController.php)
  3. Define Routes

    // routes/web.php
    Route::resource('blog', BlogController::class);
    
  4. Extend ResourceController

    // BlogController.php
    use LaravelAdmin\Crud\Controllers\ResourceController;
    
    class BlogController extends ResourceController
    {
        protected $model = Blog::class;
        protected $singular_name = "blog";
        protected $plural_name = "blogs";
    }
    
  5. First Use Case Visit /blog to see a pre-built CRUD interface with:

    • List view (index)
    • Create form (create)
    • Edit form (edit)
    • Delete functionality (destroy)

Implementation Patterns

Core Workflows

  1. Field Configuration Override getFields() to define form fields:

    protected function getFields()
    {
        return [
            'title' => 'text',
            'content' => 'textarea',
            'published_at' => 'datetime',
        ];
    }
    
  2. Validation Rules Override getValidationRulesOnStore()/getValidationRulesOnUpdate():

    protected function getValidationRulesOnStore()
    {
        return [
            'title' => 'required|string|min:6',
            'content' => 'required|string',
        ];
    }
    
  3. Customizing List Columns Override getListColumns():

    protected function getListColumns()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'published_at' => 'Published At',
        ];
    }
    
  4. Relationships Define relationships in getRelationships():

    protected function getRelationships()
    {
        return [
            'author' => 'belongsTo:App\User',
        ];
    }
    
  5. Actions Add custom actions via getActions():

    protected function getActions()
    {
        return [
            'publish' => [
                'label' => 'Publish',
                'method' => 'POST',
                'url' => '/blog/{id}/publish',
                'button_class' => 'btn-success',
            ],
        ];
    }
    
  6. Form Customization Override getCreateFormFields()/getEditFormFields() for granular control:

    protected function getCreateFormFields()
    {
        return [
            'title' => ['type' => 'text', 'label' => 'Blog Title'],
            'content' => ['type' => 'textarea', 'label' => 'Content'],
        ];
    }
    
  7. Search & Filtering Override getSearchableFields():

    protected function getSearchableFields()
    {
        return ['title', 'content'];
    }
    
  8. Bulk Actions Enable via enableBulkActions():

    protected function enableBulkActions()
    {
        return true;
    }
    

Gotchas and Tips

Pitfalls

  1. Experimental Status

    • Avoid for production; expect breaking changes.
    • Test thoroughly in staging.
  2. Missing show Method

    • The show method is intentionally omitted. Implement manually if needed:
    public function show($id)
    {
        $blog = $this->model::findOrFail($id);
        return view('blog.show', compact('blog'));
    }
    
  3. Validation Overrides

    • Forgetting to return an array in getValidationRulesOnStore() will break validation.
    • Use ->rules() for dynamic rules:
      protected function getValidationRulesOnStore()
      {
          return [
              'title' => ['required', 'string', Rule::unique('blogs')->ignore($this->model)],
          ];
      }
      
  4. Field Type Mismatches

    • Ensure field types in getFields() match database columns (e.g., datetime vs. timestamp).
    • Use getFieldType() for custom logic:
      protected function getFieldType($field)
      {
          return match($field) {
              'published_at' => 'date',
              default => parent::getFieldType($field),
          };
      }
      
  5. Relationship Loading

    • Eager-load relationships in getListQuery() to avoid N+1 queries:
      protected function getListQuery()
      {
          return $this->model::with('author')->query();
      }
      
  6. CSRF Token Issues

    • Custom actions (e.g., publish) may fail if CSRF protection isn’t handled. Use:
      Route::post('/blog/{id}/publish', [BlogController::class, 'publish'])->name('blog.publish');
      
  7. Bootstrap Dependency

    • Views rely on Bootstrap 4/5. Conflicts may arise with custom CSS/JS. Override views in resources/views/vendor/laravel-admin/crud.

Debugging Tips

  1. Log Queries Enable Laravel debugging:

    DEBUG_BAR=true
    DB_DEBUG=true
    
  2. Check Controller Methods

    • Override getListData() to inspect query results:
      protected function getListData()
      {
          $data = parent::getListData();
          \Log::info('List Data:', $data);
          return $data;
      }
      
  3. Validation Errors

    • Dump validation rules and errors:
      protected function store()
      {
          $rules = $this->getValidationRulesOnStore();
          $validator = Validator::make(request()->all(), $rules);
          \Log::info('Validation Rules:', $rules);
          \Log::info('Validation Errors:', $validator->errors());
          // ...
      }
      
  4. View Rendering

    • Override getView() to debug rendered views:
      protected function getView($method)
      {
          $view = parent::getView($method);
          \Log::info("Rendering view: $view");
          return $view;
      }
      

Extension Points

  1. Custom Views

    • Override default views by publishing assets:
      php artisan vendor:publish --tag=laravel-admin-crud-views
      
    • Modify resources/views/vendor/laravel-admin/crud/.
  2. API Integration

    • Extend for API responses by overriding getListData():
      public function index()
      {
          return response()->json($this->getListData());
      }
      
  3. Middleware

    • Apply middleware to specific actions:
      public function store()
      {
          $this->middleware('auth.admin')->only(['store']);
          // ...
      }
      
  4. Events

    • Listen for CRUD events (e.g., creating, created):
      $this->model::creating(function ($model) {
          $model->user_id = auth()->id();
      });
      
  5. Localization

    • Override labels/placeholders via language files:
      // config/laravel-admin-crud.php
      'labels' => [
          'blog' => [
              'singular' => 'Post',
              'plural' => 'Posts',
          ],
      ],
      
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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