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

Laratrust Ingest Laravel Package

vizrex/laratrust-ingest

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require vizrex/laratrust-ingest
    

    Ensure santigarcor/laratrust is also installed (required dependency).

  2. Publish Configuration (if needed)

    php artisan vendor:publish --provider="Vizrex\LaratrustIngest\LaratrustIngestServiceProvider"
    

    (Note: The package may not require config; verify via config/laratrust-ingest.php if it exists.)

  3. Prepare CSV File

    • Follow the CSV format strictly.
    • Use the sample CSV as a template.
    • Example structure:
      permission_name,permission_display_name,permission_description,super-admin;Super Admin,admin;Admin
      create_post,Create Post,Allows users to create posts,y,n
      
  4. Run the Command

    php artisan roles-and-permissions:update /path/to/your/file.csv
    
    • Warning: This truncates permissions, roles, and their pivot tables. Backup data first.

First Use Case: Initial Role/Permission Setup

  • Use this package to bulk-import roles and permissions during project kickoff or major refactoring.
  • Ideal for teams where permissions are static (e.g., admin panels, SaaS platforms).
  • Alternative: Manually define roles/permissions in database/seeds/ for dynamic systems.

Implementation Patterns

Workflow: CSV-Driven Permission Management

  1. Design CSV Structure

    • Align columns with your application’s roles (e.g., super-admin, editor, viewer).
    • Use y/n for granular permission assignment (e.g., y for edit_post, n for delete_post).
  2. Version Control CSV Files

    • Store CSV files in storage/permissions/ or resources/data/.
    • Commit to Git for traceability (e.g., permissions_v1.csv, permissions_v2.csv).
  3. Automate with Artisan

    • Add to post-deploy scripts (e.g., Laravel Forge/Envoyer):
      php artisan roles-and-permissions:update storage/permissions/latest.csv
      
    • Pro Tip: Use Laravel’s Artisan::call() in a custom command for pre-processing (e.g., validate CSV before truncation).
  4. Integration with Laratrust

    • Leverage Laratrust’s hasRole() and hasPermission() in policies/controllers:
      if (auth()->user()->hasPermission('create_post')) {
          // Allow action
      }
      

Advanced Patterns

  • Dynamic Role Assignment Combine with Laravel’s Event system to auto-assign roles on user creation:

    // In UserObserver or service provider
    event(new Registered($user));
    $user->attachRole('default'); // Assign role post-import
    
  • Partial Updates

    • For large systems, split CSV by role (e.g., admin_permissions.csv, user_permissions.csv).
    • Run commands sequentially to avoid full truncation.
  • Testing Use php artisan roles-and-permissions:update tests/data/test_permissions.csv in phpunit.xml:

    <env key="DB_DATABASE" value="laratrust_testing"/>
    

Gotchas and Tips

Pitfalls

  1. Data Loss Warning

    • The command truncates all tables. Always:
      • Backup with php artisan db:backup (spatie/laravel-backup).
      • Test in a staging environment first.
    • Workaround: Use Laratrust’s Role::create() and Permission::create() for incremental updates.
  2. CSV Parsing Errors

    • Symptom: Command fails silently or creates malformed roles.
    • Fix:
      • Validate CSV with a library like league/csv before ingestion.
      • Check for:
        • Missing semicolons in role names (e.g., admin instead of admin;Admin).
        • Extra commas or quotes in permission names/descriptions.
  3. Laratrust Version Mismatch

    • Symptom: Package fails with Class 'Laratrust\Permission' not found.
    • Fix: Ensure santigarcor/laratrust is installed and configured in config/laratrust.php.
  4. Case Sensitivity

    • Role/permission names are case-sensitive. Use consistent casing in CSV (e.g., Super-Admin vs. super-admin).

Debugging Tips

  • Enable Query Logging Add to AppServiceProvider:

    public function boot()
    {
        if (app()->environment('local')) {
            DB::enableQueryLog();
        }
    }
    

    Check logs after running the command to verify SQL queries.

  • Dry Run Mode

    • The package lacks a dry-run flag. Workaround:
      php artisan roles-and-permissions:update file.csv --dry-run  # Not native; use a wrapper command
      
    • Create a custom command to log changes without executing:
      public function handle()
      {
          $csv = new \League\Csv\Reader(fopen($this->argument('csvFilePath'), 'r'));
          // Parse and log changes without DB operations
      }
      

Extension Points

  1. Custom Validation Extend the package by overriding the command:

    // app/Console/Commands/UpdateRolesAndPermissions.php
    namespace App\Console\Commands;
    use Vizrex\LaratrustIngest\Commands\UpdateRolesAndPermissions as BaseCommand;
    
    class UpdateRolesAndPermissions extends BaseCommand
    {
        protected function validateCsv(array $data)
        {
            // Add custom rules (e.g., reject empty permission names)
        }
    }
    
  2. Post-Processing Hooks Use Laravel’s events to trigger actions after ingestion:

    // In a service provider
    \Vizrex\LaratrustIngest\Events\RolesPermissionsUpdated::listen(function ($roles, $permissions) {
        // Sync with external systems (e.g., API calls)
    });
    
  3. GUI Alternative For non-technical users, pair with a package like spatie/laravel-permission + a form builder (e.g., Nova/Vue) to manually assign permissions.


Configuration Quirks

  • No Config File: The package may rely on Laratrust’s default config (config/laratrust.php).
  • Table Prefixes: If Laratrust uses prefixes (e.g., lt_), ensure the CSV logic accounts for them (unlikely, but verify with php artisan schema:dump).
  • Timeouts: Large CSV files may hit MySQL timeouts. Increase max_execution_time in php.ini or chunk the import:
    // In the package’s logic, add batch processing
    DB::statement('SET SESSION max_execution_time=300;');
    
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle