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

Utils Laravel Package

dontdrinkandroot/utils

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation Add the package via Composer:

    composer require dontdrinkandroot/utils
    

    Register the facade (if used) in config/app.php under aliases:

    'Utils' => Dontdrinkandroot\Utils\Facades\Utils::class,
    
  2. First Use Case Use the Utils facade or helper directly in a Laravel controller or service:

    use Dontdrinkandroot\Utils\Facades\Utils;
    
    // Example: Generate a random string
    $randomString = Utils::randomString(10);
    
    // Example: Check if a string is sluggable
    $isSluggable = Utils::isSluggable('test-string');
    
  3. Key Classes to Explore

    • Utils facade (main entry point)
    • StringUtils (string manipulation)
    • ArrayUtils (array operations)
    • FileUtils (file handling)
    • DateUtils (date/time utilities)

    Check the source code for full functionality.


Implementation Patterns

Common Workflows

1. String Manipulation

  • Slug Generation
    $slug = Utils::slugify('Hello World!', '-');
    // Output: 'hello-world'
    
  • Validation
    if (Utils::isEmail('test@example.com')) {
        // Process email
    }
    

2. Array Operations

  • Deep Merge
    $merged = Utils::arrayMergeRecursive([
        'key' => 'value1'
    ], [
        'key' => 'value2',
        'nested' => ['key' => 'value']
    ]);
    // Output: ['key' => 'value2', 'nested' => ['key' => 'value']]
    
  • Diffing
    $diff = Utils::arrayDiffAssoc([
        'a' => 1, 'b' => 2
    ], [
        'a' => 1, 'b' => 3
    ]);
    // Output: ['b' => 2]
    

3. File Handling

  • Read/Write Files
    Utils::writeFile('path/to/file.txt', 'Hello World');
    $content = Utils::readFile('path/to/file.txt');
    
  • Directory Operations
    Utils::createDirectory('storage/app/public/uploads');
    

4. Date/Time Utilities

  • Formatting
    $formatted = Utils::formatDate('2023-01-01', 'Y-m-d H:i:s');
    // Output: '2023-01-01 00:00:00'
    
  • Time Differences
    $diff = Utils::timeDifference('2023-01-01', '2023-01-02');
    // Output: 1 day(s)
    

5. Integration with Laravel Services

  • Custom Validation Rules
    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($request->all(), [
        'username' => ['required', function ($attribute, $value, $fail) {
            if (!Utils::isSluggable($value)) {
                $fail('The '.$attribute.' must be sluggable.');
            }
        }]
    ]);
    
  • Middleware for String Sanitization
    public function handle($request, Closure $next) {
        $request->merge([
            'sanitized_input' => Utils::sanitizeInput($request->input('user_input'))
        ]);
        return $next($request);
    }
    

6. Helper Functions in Blade

Add to composer.json under autoload.aliases:

"Dontdrinkandroot\\Utils\\Helpers" => "src/Helpers"

Then use in Blade:

{{ Utils::truncate('This is a long string', 10) }}

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • The package uses Dontdrinkandroot\Utils namespace. Ensure no naming collisions with other packages or custom classes.
    • Fix: Use fully qualified namespaces or aliases consistently.
  2. File Handling Permissions

    • FileUtils methods may fail silently if permissions are insufficient.
    • Fix: Verify storage directory permissions (e.g., chmod -R 775 storage).
  3. Deprecated PHP Features

    • The package was last updated in 2020 and may use older PHP features (e.g., create_function).
    • Fix: Test thoroughly in your PHP version (7.4+ recommended).
  4. No Laravel-Specific Optimizations

    • The package is generic PHP. Some methods (e.g., arrayMergeRecursive) may not leverage Laravel’s built-in helpers like array_merge_recursive.
    • Tip: Prefer Laravel’s native methods where available (e.g., collect()->merge()).
  5. Limited Error Handling

    • Some methods (e.g., readFile) lack robust error handling for edge cases (e.g., file not found).
    • Tip: Wrap in try-catch:
      try {
          $content = Utils::readFile('file.txt');
      } catch (\Exception $e) {
          Log::error($e->getMessage());
          $content = null;
      }
      

Debugging Tips

  1. Enable Strict Typing Add to composer.json to catch type-related issues early:

    "config": {
        "platform-check": true,
        "platform": {
            "php": "8.0"
        }
    }
    
  2. Log Utility Outputs Debug complex operations like arrayDiffAssoc:

    $diff = Utils::arrayDiffAssoc($array1, $array2);
    Log::debug('Array Diff:', ['diff' => $diff]);
    
  3. Test Edge Cases

    • Empty strings, null values, or malformed inputs may break assumptions.
    • Example:
      Utils::slugify(null); // May return null or throw an error.
      

Extension Points

  1. Customize Slug Generation Override the slugify method in a service provider:

    Utils::extend('slugify', function ($string, $separator = '-') {
        // Custom logic
        return strtolower(preg_replace('/[^a-z0-9]+/', $separator, $string));
    });
    
  2. Add Laravel-Specific Helpers Create a custom facade or trait to bridge Laravel and the package:

    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    use Dontdrinkandroot\Utils\Facades\Utils as BaseUtils;
    
    class Utils extends Facade {
        protected static function getFacadeAccessor() {
            return BaseUtils::class;
        }
    
        public static function laravelSlug($string) {
            return static::slugify($string, '-');
        }
    }
    
  3. Integrate with Laravel Events Use the package in event listeners (e.g., sanitizing input on creating):

    public function handle($event) {
        $event->model->name = Utils::sanitizeInput($event->model->name);
    }
    
  4. Performance Optimization

    • Cache repeated operations (e.g., slug generation) using Laravel’s cache:
      $slug = Cache::remember("slug_{$input}", now()->addHours(1), function() use ($input) {
          return Utils::slugify($input);
      });
      

Configuration Quirks

  • No Config File: The package has no Laravel-specific config. All settings are method arguments.
  • Default Values: Some methods use hardcoded defaults (e.g., randomString uses alphanum by default). Override via method parameters:
    Utils::randomString(10, 'abc123'); // Custom character set
    
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle