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 Time Craft Laravel Package

omaralalwi/laravel-time-craft

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require omaralalwi/laravel-time-craft
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="OmarAlalwi\TimeCraft\TimeCraftServiceProvider"
    
  2. First Use Case: Apply a built-in scope to a query:

    use OmarAlalwi\TimeCraft\Scopes\TodayScope;
    
    $todayRecords = Model::query()->today()->get();
    
  3. Key Entry Points:

    • Traits: OmarAlalwi\TimeCraft\Traits\TimeCraft (for models).
    • Scopes: OmarAlalwi\TimeCraft\Scopes\* (e.g., TodayScope, YesterdayScope).
    • Helpers: OmarAlalwi\TimeCraft\Helpers\TimeCraft (e.g., formatDate(), humanizeTime()).

Implementation Patterns

Core Workflows

  1. Model Integration: Use the trait in your Eloquent models to auto-apply scopes:

    use OmarAlalwi\TimeCraft\Traits\TimeCraft;
    
    class Event extends Model
    {
        use TimeCraft;
    }
    

    Now call scopes directly:

    Event::thisWeek()->get();
    
  2. Query Builder Usage: Attach scopes dynamically:

    $query = Model::query();
    $query->applyScopes(['thisMonth', 'active']);
    
  3. Custom Scopes: Extend existing scopes or create new ones:

    namespace App\Scopes;
    
    use OmarAlalwi\TimeCraft\Scopes\BaseScope;
    
    class CustomScope extends BaseScope
    {
        protected $field = 'created_at';
        protected $operator = '>=';
        protected $value = now()->subDays(7);
    
        public function apply($query)
        {
            return $query->where($this->field, $this->operator, $this->value);
        }
    }
    
  4. Helper Functions: Format dates in views or controllers:

    use OmarAlalwi\TimeCraft\Helpers\TimeCraft;
    
    $formatted = TimeCraft::formatDate(now(), 'Y-m-d H:i');
    $humanized = TimeCraft::humanizeTime(now()->subHours(3));
    
  5. API Responses: Use helpers to standardize date formats in JSON:

    return response()->json([
        'event' => [
            'date' => TimeCraft::formatDate($event->date, 'Y-m-d'),
            'time' => TimeCraft::humanizeTime($event->date),
        ],
    ]);
    
  6. Time Zone Handling: Configure default time zone in config/time-craft.php:

    'timezone' => 'America/New_York',
    

    Override per query:

    Model::query()->setTimezone('Europe/London')->thisWeek()->get();
    

Gotchas and Tips

Pitfalls

  1. Scope Conflicts:

    • If multiple scopes modify the same field (e.g., created_at), later scopes may override earlier ones.
    • Fix: Use whereRaw or chain scopes carefully:
      Model::query()->where('created_at', '>=', now()->subDays(30))->thisWeek();
      
  2. Time Zone Mismatches:

    • Scopes use the configured timezone in time-craft.php. Ensure this matches your app’s timezone.
    • Debug: Temporarily log the timezone:
      \Log::info('Timezone:', config('time-craft.timezone'));
      
  3. Dynamic Field Names:

    • Scopes assume default fields (e.g., created_at). Override in custom scopes:
      protected $field = 'published_at';
      
  4. Helper Caching:

    • humanizeTime() caches results for 1 hour by default. Clear cache if dates change unexpectedly:
      TimeCraft::clearHumanizeCache();
      

Debugging Tips

  1. Inspect Queries: Use Laravel’s query logging to verify scope SQL:

    DB::enableQueryLog();
    Model::thisWeek()->get();
    \Log::info(DB::getQueryLog());
    
  2. Scope Order: Scopes are applied in declaration order. Reorder or use where() for control:

    Model::query()->where('status', 'active')->thisWeek();
    
  3. Edge Cases:

    • Test scopes with now() boundaries (e.g., today() at midnight).
    • Example:
      $midnight = now()->startOfDay();
      Model::where('created_at', '>=', $midnight)->today()->get();
      

Extension Points

  1. Custom Time Frames: Extend BaseScope to add reusable logic:

    class LastNDaysScope extends BaseScope
    {
        protected $days;
    
        public function __construct($days)
        {
            $this->days = $days;
        }
    
        public function apply($query)
        {
            return $query->where('created_at', '>=', now()->subDays($this->days));
        }
    }
    

    Usage:

    Model::query()->applyScopes(['lastNDays:30']);
    
  2. Localization: Override humanizeTime() translations in config/time-craft.php:

    'humanize' => [
        'minutes' => 'minute|minutes',
        'hours' => 'hour|hours',
        // ...
    ],
    
  3. Performance:

    • For large datasets, use select() to limit columns:
      Model::thisWeek()->select(['id', 'title'])->get();
      
    • Cache frequent queries with remember():
      $todayEvents = cache()->remember("events.today", now(), function () {
          return Event::today()->get();
      });
      
  4. Testing: Mock time in tests:

    use OmarAlalwi\TimeCraft\Facades\TimeCraft;
    
    TimeCraft::shouldReceive('now')->andReturn($mockedDate);
    
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