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 Useful Traits Laravel Package

laracraft-tech/laravel-useful-traits

Laravel package with handy daily-use additions: traits for PHP 8.1+ enums (get names/values/array) and Eloquent query scopes (e.g., select all columns except specific ones, date-based scopes), plus an Artisan db:truncate command.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer:

composer require laracraft-tech/laravel-useful-traits

First Use Case: Enums For PHP 8.1+ projects, immediately leverage UsefulEnums to convert enums to arrays:

enum Status: string {
    use \LaracraftTech\LaravelUsefulAdditions\Traits\UsefulEnums;
    case Active = 'active';
    case Pending = 'pending';
}

// Usage:
Status::names();   // ['Active', 'Pending']
Status::array();   // ['Active' => 'active', 'Pending' => 'pending']

First Use Case: Query Scopes Add UsefulScopes to a model for reusable time-based queries:

use LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes;

class Order extends Model {
    use UsefulScopes;
}

// Usage:
Order::fromToday()->get(); // Orders created today
Order::fromYesterday()->get(); // Orders created yesterday

First Use Case: Database Truncation Reset development databases with:

php artisan db:truncate --force

Implementation Patterns

Enum Integration

  1. Type Safety: Replace magic strings with enums for domain models (e.g., UserRole, OrderStatus).
  2. Migration Helper: Use Status::array() to populate migration tables:
    Schema::create('statuses', function (Blueprint $table) {
        $table->string('name')->unique();
        $table->string('value');
    });
    
    DB::table('statuses')->insert(array_values(Status::array()));
    
  3. Form Validation: Bind enum values to request validation:
    use App\Enums\Status;
    
    public function rules() {
        return [
            'status' => ['required', Rule::in(Status::values())],
        ];
    }
    

Query Scope Patterns

  1. Model-Level Scopes: Attach UsefulScopes to base models for global reuse:
    class BaseModel extends Model {
        use UsefulScopes;
    }
    
  2. Dynamic Field Exclusion: Use selectAllBut() for API responses:
    // Exclude sensitive fields from API
    User::selectAllBut(['password', 'api_token'])->get();
    
  3. Composite Scopes: Chain with Laravel’s built-in scopes:
    Order::where('user_id', auth()->id())
         ->fromToday()
         ->orderBy('created_at', 'desc')
         ->get();
    

Database Management

  1. CI/CD Pipelines: Use db:truncate in .github/workflows/:
    - name: Reset DB
      run: php artisan db:truncate --force
    
  2. Local Development: Alias the command in ~/.bashrc:
    alias dbreset='php artisan db:truncate --force'
    
  3. Partial Truncation: Target specific tables:
    php artisan db:truncate --tables=orders,users
    

Testing Workflows

  1. Pest Integration: Replace RefreshDatabase with UsefulScopes for targeted queries:
    use LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes;
    
    it('filters recent orders', function () {
        Order::factory()->create(['created_at' => now()->yesterday()]);
        expect(Order::fromToday()->count())->toBe(0);
    });
    
  2. Performance Testing: Compare db:truncate vs. migrate:fresh in benchmarks.

Gotchas and Tips

UsefulEnums

  • PHP Version: Requires PHP 8.1+. Use array_map(fn($e) => $e->value, Status::cases()) as a fallback for older versions.
  • Backward Compatibility: For Laravel <10, use collect(Status::cases())->pluck('value').
  • Performance: Status::array() caches results internally; avoid calling it in loops.

UsefulScopes

  • Column Cache: Clear cache after migrations:
    php artisan cache:clear
    
    Or manually:
    \LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes::clearCache();
    
  • MySQL Limitation: selectAllBut() queries all columns first, then filters. For large tables, explicitly list columns:
    User::select(['id', 'name', 'email'])->selectAllBut(['password']);
    
  • Time Zone Awareness: fromToday()/fromYesterday() use the system timezone. Override with:
    Order::fromToday()->where('created_at', '>=', now()->setTimezone('UTC')->startOfDay());
    

db:truncate

  • Foreign Keys: Disable checks for complex schemas:
    php artisan db:truncate --disable-foreign-keys
    
  • Excluded Tables: Protect critical tables (e.g., migrations):
    php artisan db:truncate --exclude=migrations,failed_jobs
    
  • Transactions: Wrapped in a transaction by default. For large databases, disable with --no-transaction.

Debugging

  1. Enum Issues: Verify PHP version with:
    php -r "echo PHP_VERSION;"
    
  2. Scope Failures: Check cached columns:
    \LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes::getCachedColumns('users');
    
  3. Truncate Errors: Inspect the full command output for table-specific failures.

Extension Points

  • Custom Scopes: Extend UsefulScopes in a base model:
    trait CustomScopes {
        public function scopeActiveOnly($query) {
            return $query->where('is_active', true);
        }
    }
    
  • Enum Methods: Add static methods to enums:
    enum Status {
        use UsefulEnums;
    
        public static function getActive(): array {
            return [self::Active];
        }
    }
    
  • Command Hooks: Override db:truncate logic by publishing the config:
    php artisan vendor:publish --tag="useful-additions-config"
    
    Then extend the TruncateCommand class in config/useful-additions.php.

Performance

  • Enum Arrays: Cache Status::array() in a service provider if used frequently:
    public function boot() {
        Status::setCacheDriver('array');
    }
    
  • Scope Optimization: For selectAllBut(), pre-fetch columns in a service:
    $columns = \LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes::getCachedColumns('users');
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope