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

miladimos/laravel-toolkit

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require miladimos/laravel-toolkit
    php artisan toolkit:install
    

    This generates the default helpers.php file in app/Helpers/.

  2. First Use Case:

    • UUID Generation: Use the RouteKeyNameUUID trait in a model to auto-generate UUIDs for route keys and database IDs:
      use Miladimos\Toolkit\Traits\RouteKeyNameUUID;
      
      class Post extends Model
      {
          use RouteKeyNameUUID;
      }
      
    • API Responses: Leverage ApiResponder for consistent JSON responses:
      use Miladimos\Toolkit\Traits\ApiResponder;
      
      class PostController extends Controller
      {
          use ApiResponder;
      
          public function show(Post $post)
          {
              return $this->successResponse($post);
          }
      }
      
  3. Where to Look First:

    • Traits: Browse app/Helpers/helpers.php (auto-generated) for helper methods.
    • Documentation: Check the GitHub README for trait-specific usage.
    • Artisan Commands: Use php artisan make:helper to scaffold new helper files.

Implementation Patterns

Common Workflows

  1. Model Enhancements:

    • UUIDs: Combine HasUUID and RouteKeyNameUUID for UUID-based models:
      use Miladimos\Toolkit\Traits\{HasUUID, RouteKeyNameUUID};
      
      class Comment extends Model
      {
          use HasUUID, RouteKeyNameUUID;
      }
      
    • Timestamps: Use HasTimestamps to enforce created_at/updated_at:
      use Miladimos\Toolkit\Traits\HasTimestamps;
      
      class LogEntry extends Model
      {
          use HasTimestamps;
      }
      
  2. API Layer:

    • Standardized Responses: Replace manual return response()->json() with ApiResponder:
      return $this->errorResponse('Invalid data', 422, ['errors' => $validator->errors()]);
      
    • JWT Handling: Use HasJWT in controllers for token logic:
      use Miladimos\Toolkit\Traits\HasJWT;
      
      class AuthController extends Controller
      {
          use HasJWT;
      
          public function login(Request $request)
          {
              return $this->generateJWT($user);
          }
      }
      
  3. Helper Methods:

    • Custom Helpers: Extend helpers.php with reusable logic:
      if (!function_exists('slugify')) {
          function slugify(string $text): string
          {
              return Str::slug($text);
          }
      }
      
    • Enum Constants: Use GetConstantsEnum for type-safe constants:
      use Miladimos\Toolkit\Traits\GetConstantsEnum;
      
      class UserRole
      {
          use GetConstantsEnum;
      
          const ADMIN = 'admin';
          const USER = 'user';
      }
      
  4. Relationships:

    • Tags: Attach tags to models with HasTags:
      use Miladimos\Toolkit\Traits\HasTags;
      
      class Article extends Model
      {
          use HasTags;
      }
      
    • Comments: Add commentable behavior with HasComment:
      use Miladimos\Toolkit\Traits\HasComment;
      
      class BlogPost extends Model
      {
          use HasComment;
      }
      
  5. Integration Tips:

    • Service Providers: Register helper files in config/autoload.php:
      'files' => [
          app_path('Helpers/helpers.php'),
      ],
      
    • Testing: Mock traits in tests by extending their methods:
      $mock = $this->getMockForTrait(ApiResponder::class);
      

Gotchas and Tips

Pitfalls

  1. Trait Conflicts:

    • Issue: Overlapping methods (e.g., boot() in HasUUID vs. HasTimestamps).
    • Fix: Review trait methods before combining them. Use protected overrides if needed:
      protected static function bootHasUUID()
      {
          // Custom logic
      }
      
  2. UUID Generation:

    • Issue: RouteKeyNameUUID may clash with Laravel’s default incrementing behavior.
    • Fix: Explicitly set $incrementing = false and $keyType = 'string' in your model.
  3. Helper Autoloading:

    • Issue: New helper files aren’t autoloaded after creation.
    • Fix: Run composer dump-autoload or update composer.json manually.
  4. JWT Traits:

    • Issue: HasJWT assumes tymon/jwt-auth is installed.
    • Fix: Install the package first:
      composer require tymon/jwt-auth
      
  5. Database Migrations:

    • Issue: HasUUID or HasTimestamps may not auto-create columns.
    • Fix: Manually add columns or extend the trait’s boot() method to create migrations dynamically.

Debugging

  1. Trait Methods Not Loading:

    • Verify the trait is used in the correct class.
    • Check for typos in trait names (e.g., HasJWT vs. HasJwt).
  2. API Response Issues:

    • ApiResponder uses response()->json(). Ensure your Laravel version supports it (v5.5+).
    • Override successResponse() or errorResponse() for custom logic:
      public function successResponse($data, int $status = 200, array $headers = [])
      {
          return response()->json(['data' => $data], $status, $headers);
      }
      
  3. Enum Constants:

    • GetConstantsEnum requires PHP 7.1+. For older versions, manually define constants.

Tips

  1. Organize Helpers:

    • Split helpers.php into modular files (e.g., StringHelpers.php, ArrayHelpers.php) and autoload them:
      'files': [
          app_path('Helpers/StringHelpers.php'),
          app_path('Helpers/ArrayHelpers.php'),
      ],
      
  2. Extend Traits:

    • Create custom traits extending the package’s traits for project-specific logic:
      namespace App\Traits;
      
      use Miladimos\Toolkit\Traits\HasUUID;
      
      trait CustomUUID extends HasUUID
      {
          public function generateCustomUUID()
          {
              return Str::uuid()->toString();
          }
      }
      
  3. Performance:

    • UUIDs: Cache UUID generation if used frequently (e.g., in loops).
    • Traits: Avoid overusing traits in small classes; prefer composition for clarity.
  4. Testing:

    • Test trait methods in isolation:
      $model = new class extends Model {
          use HasUUID;
      };
      $this->assertNotNull($model->uuid);
      
  5. Configuration:

    • Override default behavior via config (if the package supports it). Example for ApiResponder:
      'api_responder' => [
          'default_status' => 200,
          'wrap_data' => true,
      ],
      
    • Note: Check if the package includes a config file (e.g., config/toolkit.php).
  6. Localization:

    • The package supports Persian (README-fa.md). Use php artisan lang:publish to customize translations if needed.
  7. Backward Compatibility:

    • Test with Laravel 5.8+ (the package’s likely target). Some features (e.g., ApiResponder) may need adjustments for older versions.
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