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

Essentials Laravel Package

nunomaduro/essentials

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nunomaduro/essentials
    

    Publish the config (optional but recommended for customization):

    php artisan vendor:publish --provider="NunoMaduro\Essentials\EssentialsServiceProvider" --tag="config"
    
  2. First Use Case:

    • Strict Models: Create a model with use \NunoMaduro\Essentials\Strict\Concerns\StrictModel; and add $guarded = []; to enforce strict property access.
    • Immutable Dates: Use use \NunoMaduro\Essentials\Immutable\Concerns\ImmutableDate; to make dates immutable in your models.
  3. Where to Look First:

    • Config File: config/essentials.php (for customizing behavior like strictness levels, default eager loads, etc.).
    • Model Traits: Review StrictModel, ImmutableDate, and AutoEagerLoad traits in vendor/nunomaduro/essentials/src/Strict/Concerns and src/Immutable/Concerns.
    • Artisan Commands: Run php artisan essentials:install to scaffold common files (e.g., .env.example, routes/web.php, routes/api.php).

Implementation Patterns

Core Workflows

  1. Strict Models:

    • Usage: Extend StrictModel in your Eloquent models to enforce strict property access.
      use NunoMaduro\Essentials\Strict\Concerns\StrictModel;
      
      class User extends Model
      {
          use StrictModel;
      
          protected $guarded = []; // Only allow mass assignment for these fields
      }
      
    • Benefit: Prevents accidental mass assignment of non-whitelisted attributes and enforces type safety.
  2. Auto-Eager Loading:

    • Usage: Define $autoEagerLoad in your models to automatically eager load relationships.
      class User extends Model
      {
          use \NunoMaduro\Essentials\AutoEagerLoad\Concerns\AutoEagerLoad;
      
          protected $autoEagerLoad = ['posts', 'comments']; // Relationships to always eager load
      }
      
    • Integration Tip: Useful for reducing N+1 queries in complex queries or API responses. Combine with with() in queries to override defaults:
      User::with(['posts' => function ($query) {
          $query->where('published', true);
      }])->get();
      
  3. Immutable Dates:

    • Usage: Apply the ImmutableDate trait to models to ensure dates cannot be modified after creation.
      use NunoMaduro\Essentials\Immutable\Concerns\ImmutableDate;
      
      class Post extends Model
      {
          use ImmutableDate;
      
          protected $dates = ['published_at'];
      }
      
    • Workflow: Dates like published_at will throw exceptions if modified after initialization.
  4. Artisan Commands:

    • Common Commands:
      • php artisan essentials:install: Scaffold boilerplate files.
      • php artisan essentials:strict:check: Validate models for strict compliance.
      • php artisan essentials:immutable:check: Validate immutable date usage.
  5. Testing:

    • Mocking: Use EssentialsServiceProvider in tests to isolate behavior:
      $this->app->register(\NunoMaduro\Essentials\EssentialsServiceProvider::class);
      

Integration Tips

  • Laravel Forge/C Forge: Use the essentials:install command to standardize new projects.
  • APIs: Combine AutoEagerLoad with apiResources to optimize response times.
  • Migrations: Use StrictModel to catch invalid column names early via $fillable/$guarded mismatches.

Gotchas and Tips

Pitfalls

  1. Strict Models:

    • Mass Assignment Errors: Forgetting to add a field to $guarded or $fillable will throw MassAssignmentException. Always validate with:
      php artisan essentials:strict:check
      
    • Dynamic Properties: Avoid dynamic property access (e.g., $model->dynamicProp = 'value') unless explicitly allowed in $guarded.
  2. Auto-Eager Loading:

    • Performance Overhead: Over-eager loading can bloat queries. Monitor with Laravel Debugbar or DB::enableQueryLog().
    • Circular Relationships: Auto-eager loading may cause infinite loops. Exclude circular relationships or use with() to limit depth.
  3. Immutable Dates:

    • Runtime Errors: Attempting to modify an immutable date (e.g., $post->published_at = now()) throws ImmutableDateException. Use setters or factory methods instead:
      $post->setPublishedAt(now());
      
    • Serialization: Immutable dates may cause issues with JSON serialization. Use accessors:
      public function getPublishedAtAttribute($value) {
          return $value->toDateTimeString();
      }
      
  4. Configuration:

    • Global Strictness: The strict config key in essentials.php defaults to true. Set to false to disable strict checks globally (not recommended for production).
    • Eager Load Limits: The max_auto_eager_load_depth config prevents stack overflows in deeply nested relationships.
  5. Testing:

    • Mocking Exceptions: Use partial mocks to test strict/immutable behavior:
      $model = $this->partialMock(User::class, ['setAttribute']);
      $model->shouldReceive('setAttribute')->andThrow(ImmutableDateException::class);
      

Debugging Tips

  • Strict Model Issues: Enable Laravel's debugbar to inspect mass assignment payloads.
  • Auto-Eager Load Queries: Use DB::listen() to log generated queries:
    DB::listen(function ($query) {
        \Log::debug($query->sql, $query->bindings);
    });
    
  • Immutable Dates: Check for ImmutableDateException in logs or use a try-catch block to handle gracefully:
    try {
        $post->published_at = now();
    } catch (ImmutableDateException $e) {
        \Log::warning('Attempted to modify immutable date', ['model' => $post]);
    }
    

Extension Points

  1. Custom Traits:

    • Extend existing traits (e.g., StrictModel) to add domain-specific validation:
      trait CustomStrictModel extends StrictModel {
          public function setAttribute($key, $value) {
              if ($key === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                  throw new \InvalidArgumentException('Invalid email format.');
              }
              parent::setAttribute($key, $value);
          }
      }
      
  2. Dynamic Eager Loading:

    • Override getAutoEagerLoad() in models for dynamic behavior:
      public function getAutoEagerLoad()
      {
          return request()->user()->isAdmin() ? ['posts', 'users'] : ['posts'];
      }
      
  3. Immutable Attributes:

    • Extend ImmutableDate to support other immutable fields (e.g., UUIDs):
      use NunoMaduro\Essentials\Immutable\Concerns\ImmutableAttribute;
      
      trait ImmutableUuid {
          use ImmutableAttribute;
      
          protected $immutableAttributes = ['uuid'];
      }
      
  4. Artisan Commands:

    • Register custom commands in EssentialsServiceProvider:
      $this->commands([
          \App\Console\Commands\CustomEssentialsCommand::class,
      ]);
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor