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 Admin Laravel Package

encore/laravel-admin

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require encore/laravel-admin
    php artisan admin:install
    

    This publishes config, migrations, and assets, and sets up the default admin route (/admin).

  2. First Use Case: Create a CRUD interface for a User model in 3 steps:

    php artisan admin:make User
    
    • Edit app/Admin/Controllers/UserController.php to define fields:
      public function fields()
      {
          return [
              ID::make()->sortable(),
              Text::make('name')->sortable(),
              Email::make('email')->sortable(),
              // ...
          ];
      }
      
    • Run migrations and test at /admin/users.
  3. Key Files to Review:

    • config/admin.php (core settings)
    • app/Admin/Controllers/ (custom controllers)
    • resources/views/vendor/adminlte/ (custom templates)

Implementation Patterns

Core Workflows

  1. Model-Based CRUD:

    • Use php artisan admin:make ModelName to scaffold controllers.
    • Customize via fields(), form(), title(), and listRow() methods in controllers.
  2. Field Types:

    • Basic: ID, Text, Email, Boolean, Image, Markdown.
    • Relationships: BelongsTo, HasOne, HasMany, BelongsToMany.
    • Custom: Extend FormField or Column classes.
  3. Form Customization:

    public function form()
    {
        return [
            Text::make('name')->rules('required|max:255'),
            Password::make('password')->onlyShowWhenCreating(),
            Select::make('role')->options(['admin' => 'Admin', 'user' => 'User']),
        ];
    }
    
  4. List Views:

    public function list()
    {
        return $this->table->columns([
            ID::make()->sortable(),
            Text::make('name')->sortable()->searchable(),
            Boolean::make('active')->sortable(),
        ]);
    }
    
  5. Actions:

    public function action()
    {
        return Action::make('Delete')
            ->icon('fa fa-trash')
            ->ajax(['method' => 'DELETE'])
            ->confirm('Are you sure?');
    }
    
  6. Integration with Laravel:

    • Use Laravel’s Eloquent models directly.
    • Leverage Laravel’s validation, policies, and middleware (e.g., can('manage-users', $user)).
  7. Authentication:

    • Default: Uses Laravel’s built-in auth (configure in config/admin.php).
    • Custom: Extend AdminAuth or override AuthServiceProvider.
  8. API Endpoints:

    • Generate API routes for models:
      php artisan admin:make User --api
      
    • Access via /admin/api/users.

Advanced Patterns

  1. Dynamic Fields:

    Text::make('dynamic_field')->visible(function () {
        return request()->input('show_dynamic');
    });
    
  2. Reusable Components:

    • Create base controllers for shared logic:
      class BaseController extends Controller
      {
          public function title()
          {
              return 'Base Title';
          }
      }
      
  3. Event Handling:

    • Listen to model events (e.g., creating, updating):
      public function onCreating()
      {
          $this->model->setAttribute('created_by', auth()->id());
      }
      
  4. Custom Views:

    • Override Blade templates in resources/views/vendor/adminlte/.
    • Example: Extend partials/form-field.blade.php.
  5. Multi-Tenancy:

    • Use middleware to scope models:
      public function scopeTenants($query)
      {
          return $query->where('tenant_id', auth()->tenant()->id);
      }
      
  6. Bulk Actions:

    public function batchActions()
    {
        return [
            Download::make()->name('download'),
            Delete::make()->name('delete'),
        ];
    }
    
  7. Form Tabs:

    public function form()
    {
        return [
            Tab::make('Basic Info', function () {
                return [
                    Text::make('name'),
                    Email::make('email'),
                ];
            }),
            Tab::make('Advanced', function () {
                return [
                    Textarea::make('bio'),
                ];
            }),
        ];
    }
    

Gotchas and Tips

Common Pitfalls

  1. Caching Issues:

    • Clear config cache after changes:
      php artisan config:clear
      
    • Disable caching in config/admin.php during development:
      'cache' => [
          'enabled' => env('APP_DEBUG') === false,
      ],
      
  2. Route Conflicts:

    • Ensure /admin doesn’t clash with other routes. Use middleware:
      Route::group(['middleware' => 'admin'], function () {
          Admin::routes();
      });
      
  3. Field Validation:

    • Rules are applied client-side (via JavaScript) and server-side. Test both:
      Text::make('name')->rules('required|unique:users,name,'.$this->rowId);
      
  4. Relationship Loading:

    • Eager load relationships to avoid N+1 queries:
      public function list()
      {
          return $this->table->model()->with('author');
      }
      
  5. Asset Compilation:

    • Run npm run dev or npm run prod if CSS/JS assets fail to load.
    • Customize assets in resources/assets/admin/.
  6. Permission Denied:

    • Ensure gates/policies are set in app/Providers/AdminServiceProvider.php:
      Gate::define('access-admin', function ($user) {
          return $user->isAdmin();
      });
      
  7. Model Events vs. Admin Events:

    • Admin events (e.g., creating, saving) are not Laravel’s Eloquent events. Use:
      public function onCreating()
      {
          // Admin-specific logic
      }
      

Debugging Tips

  1. Log Admin Events:

    • Enable debug mode in config/admin.php:
      'debug' => env('APP_DEBUG'),
      
    • Check logs at storage/logs/laravel-admin.log.
  2. Dump Data:

    • Use dd($this->model) in controller methods to inspect data.
  3. Check Request Payload:

    • Override handle() in controllers to log requests:
      public function handle()
      {
          \Log::info('Request data:', request()->all());
          parent::handle();
      }
      
  4. Database Queries:

    • Use Laravel Debugbar or DB::enableQueryLog() to inspect queries:
      public function list()
      {
          DB::enableQueryLog();
          $result = $this->table->columns([...]);
          \Log::info(DB::getQueryLog());
          return $result;
      }
      

Extension Points

  1. Custom Field Types:

    • Extend FormField or Column:
      class CustomField extends FormField
      {
          public function render()
          {
              return '<input type="text" value="' . $this->value . '">';
          }
      }
      
  2. Custom Actions:

    • Create reusable actions in app/Admin/Actions/:
      class ExportAction extends Action
      {
          public function __construct()
          {
              parent::__construct('Export');
          }
      
          public function handle()
          {
              // Custom logic
          }
      }
      
  3. Custom Middleware:

    • Add middleware to app/Http/Kernel.php:
      protected $adminMiddleware = [
          \App\Http\Middleware\CheckAdminStatus::class,
      ];
      
  4. Custom Auth:

    • Override app/Admin/Auth/AdminAuth.php:
      public function authenticate()
      {
          if (auth()->check()) {
              return true;
          }
          return false;
      }
      
  5. Custom Themes:

    • Extend AdminLTE themes by overriding resources/views/vendor/adminlte/.
  6. Custom API Responses:

    • Override app/Admin/Controllers/ApiController.php:
      public function apiIndex()
      {
          return $this->response->api()->paginate();
      }
      

Performance Tips

  1. Disable Unused Features:

    'features' => [
        'menu.builder' => false, // Disable menu builder if not needed
        'menu.i18n' => false,
    ],
    
  2. Lazy Load Relationships:

    • Use load() for relationships in list():
      $this->table->model()->with(['author' => function ($query) {
          $query->select('id', 'name');
      }]);
      
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.
milito/query-filter
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