Weave 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

Db Tools Laravel Package

laranail/db-tools

Laranail DB Tools bundles practical database utilities for Laravel, offering convenient Artisan commands and helpers to inspect schemas, manage connections, and handle routine maintenance. A handy toolkit for debugging queries and keeping your database layer tidy.

Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require laranail/db-tools
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Laranail\DbTools\DbToolsServiceProvider"
    
  2. Key Features to Explore

    • UUID/ULID Traits: Use HasUlid or HasUuid traits in your models.
      use Laranail\DbTools\Traits\HasUlid;
      
      class Post extends Model
      {
          use HasUlid;
      }
      
    • Schema Macros: Extend Eloquent schema with custom methods.
      Schema::macro('addSoftArchive', function (Blueprint $table) {
          // Custom logic
      });
      
    • Soft-Archive: Enable soft-archiving on models:
      use Laranail\DbTools\Traits\SoftArchivable;
      
      class Post extends Model
      {
          use SoftArchivable;
      }
      
    • Casts: Use built-in casts like encrypted, json, or ulid.
      protected $casts = [
          'metadata' => 'encrypted',
          'tags' => 'json',
          'id' => 'ulid',
      ];
      
  3. First Use Case Create a model with ULID and soft-archive:

    php artisan make:model Post -t=HasUlid,SoftArchivable
    

    Then run migrations to add the required columns.


Implementation Patterns

Common Workflows

  1. UUID/ULID Integration

    • Use HasUlid or HasUuid in models requiring unique identifiers.
    • Override bootHasUlid() or bootHasUuid() for custom logic (e.g., generating IDs on creation).
    • Example:
      protected static function bootHasUlid()
      {
          parent::bootHasUlid();
          static::creating(function ($model) {
              $model->{$model->getKeyName()} = Ulid::generate();
          });
      }
      
  2. Schema Macros

    • Extend Laravel’s schema builder with reusable methods.
    • Register macros in a service provider:
      Schema::macro('addTimestampsWithAudit', function (Blueprint $table) {
          $table->timestamps();
          $table->timestamp('audited_at')->nullable();
      });
      
    • Use in migrations:
      Schema::create('posts', function (Blueprint $table) {
          $table->addTimestampsWithAudit();
      });
      
  3. Soft-Archive

    • Scope queries to exclude archived records:
      $activePosts = Post::active()->get();
      
    • Archive records in bulk:
      Post::where('is_published', false)->archive();
      
    • Restore archived records:
      $post->restore();
      
  4. Database Backups

    • Trigger backups via Artisan:
      php artisan db:backup --database=mysql --path=/backups
      
    • Schedule backups in app/Console/Kernel.php:
      $schedule->command('db:backup')->daily();
      
    • Restore from backups:
      php artisan db:restore --file=/backups/backup_20260712.sql
      
  5. Custom Casts

    • Extend existing casts or create new ones in app/Providers/AppServiceProvider:
      use Laranail\DbTools\Casts\CustomCast;
      
      $this->app->bind('custom_cast', function () {
          return new CustomCast();
      });
      
    • Use in models:
      protected $casts = [
          'custom_field' => CustomCast::class,
      ];
      

Gotchas and Tips

Pitfalls and Debugging

  1. UUID/ULID Conflicts

    • Ensure your primary key column type matches the trait (e.g., ulid trait requires binary(16) for ULID).
    • If using HasUuid, confirm the column is char(36) or binary(16).
    • Debug Tip: Use php artisan tinker to test ID generation:
      use Laranail\DbTools\Traits\HasUlid;
      class TestModel extends Model { use HasUlid; }
      $model = new TestModel();
      $model->id; // Should output a ULID
      
  2. Soft-Archive Scope Issues

    • The active() scope excludes archived records by default. If you need to include them, use withArchived():
      $allPosts = Post::withArchived()->get();
      
    • Debug Tip: Check if the archived_at column exists in your migration. Missing it will cause errors.
  3. Schema Macro Overrides

    • Macros registered in service providers may be overridden by other packages. Use a unique namespace:
      Schema::macro('myapp_addIndex', function (Blueprint $table, $column) {
          $table->index($column);
      });
      
    • Debug Tip: Clear cached macros in AppServiceProvider:
      Schema::clearMacros();
      
  4. Backup/Restore Quirks

    • Ensure the --database flag matches your .env configuration.
    • Debug Tip: Test backups on a staging environment first. Restore issues often stem from:
      • Missing foreign key constraints (disable them temporarily with --skip-foreign-keys).
      • Large databases timing out (increase max_execution_time in php.ini).
    • Tip: Use --compress for large backups to save space:
      php artisan db:backup --compress
      
  5. Casts and Serialization

    • Custom casts may break serialization (e.g., JSON APIs). Test with:
      $post->toArray(); // Check if custom casts serialize correctly
      
    • Tip: Use Jsonable interface for complex casts:
      use JsonSerializable;
      
      class CustomCast implements JsonSerializable {
          public function jsonSerialize() { ... }
      }
      
  6. Migration Conflicts

    • If running migrations after adding traits, ensure the column types match:
      Schema::table('posts', function (Blueprint $table) {
          $table->binary('id')->change(); // For ULID
      });
      
    • Tip: Use Schema::hasColumn() to check for existing columns before modifying:
      if (Schema::hasColumn('posts', 'archived_at')) {
          $table->timestamp('archived_at')->nullable()->change();
      }
      

Extension Points

  1. Customizing ULID/UUID Generation

    • Override the generateId() method in your model:
      protected function generateId()
      {
          return Str::orderedUuid();
      }
      
  2. Adding Soft-Archive Events

    • Extend the SoftArchivable trait to dispatch events:
      protected static function bootSoftArchivable()
      {
          parent::bootSoftArchivable();
          static::archived(function ($model) {
              event(new PostArchived($model));
          });
      }
      
  3. Extending Backup Logic

    • Create a custom backup command:
      php artisan make:command CustomBackupCommand
      
      Then extend Laranail\DbTools\Console\Commands\BackupCommand.
  4. Adding Schema Macros for Teams

    • Organize macros by feature in a dedicated service provider:
      // app/Providers/SchemaMacrosServiceProvider.php
      Schema::macro('addTeamColumns', function (Blueprint $table) {
          $table->foreignId('team_id')->constrained();
          $table->timestamp('team_joined_at')->useCurrent();
      });
      
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.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log